rust-lang / rust

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

"Reference to data owned by current function" for a function owning no data. #130584

Open iago-lito opened 6 hours ago

iago-lito commented 6 hours ago

Code

fn f(a: &mut Vec<u64>) -> &[u64] {
    let v = a;
    v.push(1);
    &v
}

Current output

error[E0515]: cannot return reference to local variable `v`
 --> src/main.rs:4:5
  |
4 |     &v
  |     ^^ returns a reference to data owned by the current function

Desired output

Type error: expected `&[u64]`, found `& &mut Vec<u64>`.
Suggestion: change `&v` to `v`.

Rationale and extra context

It seems like the autoderef is making the borrowck confused here, or something? I had trouble interpreting the message because the function owns no data (only copy-able refs).

@Kyuuhachi I don't know the exact details, but derefing a &'local &'self mut [u64] gives a &'local [u64], not a &'self [u64] [1]

@Kyuuhachi Kind of a weird edge case here I think, because if instead chose to first relax the mutref into a &'local &'self [u64] it would be able to get a &'self [u64] from that [2]

Not sure how to help more?

Other cases

Changing &v to v makes it compile without error.

Rust Version

$ rustc --version --verbose                                                                                                                                                                          
rustc 1.83.0-nightly (f79a912d9 2024-09-18)
binary: rustc
commit-hash: f79a912d9edc3ad4db910c0e93672ed5c65133fa
commit-date: 2024-09-18
host: x86_64-unknown-linux-gnu
release: 1.83.0-nightly
LLVM version: 19.1.0

Anything else?

No response

lolbinarycat commented 5 hours ago

technically the &mut itself is owned by the function, and you are trying to return a reference to a reference