Skip to content

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

Open
@iago-lito

Description

@iago-lito

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions