Skip to content

Borrow checker bug: cannot return reference to temporary value #66541

Open
@andreytkachenko

Description

@andreytkachenko

Hi, here is an example of very strange error I have stuck with:

struct Baz {
    pub foo: &'static str
}

trait Foo {
    fn foo() -> &'static str;
}

trait Bar {
    fn bar() -> &'static [Baz];
}

struct Test;

impl Foo for Test {
    fn foo() -> &'static str {
        "Hello, World!"
    }
}

struct Bat {
    test: Test
}

impl Bar for Bat {
    fn bar() -> &'static [Baz] {
        use Foo;

        &[
            /// This compiles 
            {
                Baz { foo: "Hello, World!" }
            },
            
            /// but, this cause an error "cannot return reference to temporary value"
            {
                let foo = "Hello, World!";
                Baz { foo }
            },
            
            /// this cause an error, also
            {
                let foo = Test::foo();
                Baz { foo }
            },
            
            /// and this cause an error, too
            {
                Baz { foo: Test::foo() }
            }
        ]
    }
}

and the error message:

error[E0515]: cannot return reference to temporary value
  --> src/lib.rs:29:9
   |
29 |            &[
   |  __________^-
   | | _________|
   | ||
30 | ||             /// This compiles 
31 | ||             {
32 | ||                 Baz { foo: "Hello, World!" }
...  ||
50 | ||             }
51 | ||         ]
   | ||         ^
   | ||_________|
   | |__________returns a reference to data owned by the current function
   |            temporary value created here

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-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