rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
99.2k stars 12.81k forks source link

temporary value dropped while borrowed #132578

Open vickenty opened 1 month ago

vickenty commented 1 month ago

Code

I tried this code:

pub const fn concat(_x: &[u8], _y: &[u8]) -> [u8; 1024] {
    [0u8; 1024]
}

const _: &[u8] = &concat(
    if b"".len() > 0 {
        &concat(b"", b"")
    } else {
        b""
    },
    b""
);

I expected to see this happen: compiles

Instead, this happened: fails to compile with the following error:

error[E0716]: temporary value dropped while borrowed
 --> <source>:7:10
  |
5 | const _: &[u8] = &concat(
  |                   ------ borrow later used by call
6 |     if b"".len() > 0 {
7 |         &concat(b"", b"")
  |          ^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
8 |     } else {
  |     - temporary value is freed at the end of this statement
  |
  = note: consider using a `let` binding to create a longer lived value

Version it worked on

It most recently worked on: 1.78.0

Version with regression

rustc --version --verbose:

rustc 1.79.0 (129f3b996 2024-06-10)

@rustbot modify labels: +regression-from-stable-to-stable -regression-untriaged

vickenty commented 1 month ago

This error can be worked around by adding the freshly stabilized const {} block around the second call to concat, but I think this should not be required, given it worked fine before.

saethlin commented 1 month ago

This is https://github.com/rust-lang/rust/pull/121557. In particular, see this comment (that GitHub has hidden so the page load might be weird): https://github.com/rust-lang/rust/pull/121557#issuecomment-1990902440 You might be interested in the RFC that motivated this: https://rust-lang.github.io/rfcs/3027-infallible-promotion.html