Consider the following invalid Rust code. There is one struct Foo
that contains a reference to a second struct Bar
:
struct Foo<'a> {
bar: &'a Bar,
}
impl<'a> Foo<'a> {
fn new(bar: &'a Bar) -> Foo<'a> {
Foo { bar }
}
}
struct Bar {
value: String,
}
impl Bar {
fn empty() -> Bar {
Bar {
value: String::from("***"),
}
}
}
fn main() {
let foo = Foo::new(&Bar::empty());
println!("{}", foo.bar.value);
}
The compiler does not like this:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:24:25
|
24 | let foo = Foo::new(&Bar::empty());
| ^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
25 | println!("{}", foo.bar.value);
| ------------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
I can make it work by doing what the compiler says - using a let
binding:
fn main() {
let bar = &Bar::empty();
let foo = Foo::new(bar);
println!("{}", foo.bar.value);
}
However, suddenly I need two lines for something as trivial as instantiating my Foo
. Is there any simple way to fix this in a one-liner?