4

I have a struct that contains references to two different values. There's two constructors - one that takes a reference for each value, and one that only takes a reference to one of the values while assigning a default to the other.

My problem is assigning that default. See the code below:

struct Foo<'t> {
    a: &'t String,
    b: &'t String,
}

impl<'t> Foo<'t> {
    fn new(a: &'t String, b: &'t String) -> Foo<'t> {
        Foo { a, b }
    }

    fn new_with_default_b(a: &'t String) -> Foo<'t> {
        Foo {
            a,
            b: &String::from("default"),
        }
    }
}

This does not compile:

error[E0515]: cannot return value referencing temporary value
  --> src/lib.rs:12:9
   |
12 | /         Foo {
13 | |             a,
14 | |             b: &String::from("default"),
   | |                 ----------------------- temporary value created here
15 | |         }
   | |_________^ returns a value referencing data owned by the current function

Is it possible to fix this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Anders
  • 8,307
  • 9
  • 56
  • 88
  • 4
    Hi there! I closed your answer as duplicate. In case the linked q&a does *not* answer your question, please let us know so that we can reopen this question! In short: no, it's not possible to return a reference to a local variable (or a temporary, like in your case). It doesn't matter if the reference is returned directly or inside another struct (like in your case). – Lukas Kalbertodt Jan 13 '19 at 23:16
  • 3
    See also [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec) or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Jan 13 '19 at 23:58
  • 4
    Applying that and [How does the lifetime work on constant strings / string literals?](https://stackoverflow.com/q/31230585/155423), your code should probably [look like this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c0776adf8cbec013f5a288cb0b92e7c3). – Shepmaster Jan 14 '19 at 00:07

0 Answers0