Is there one-line syntax for constructing a struct that contains a reference to a temporary?

筅森魡賤 提交于 2020-01-30 02:52:12

问题


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?


回答1:


No, there is no such syntax, other than what you have typed.

For the details of how long a temporary lives when you take a reference to it, see:

  • Why is it legal to borrow a temporary?

There will be a parent struct owning both the bar and the foos referencing it.

Good luck:

  • Why can't I store a value and a reference to that value in the same struct?


来源:https://stackoverflow.com/questions/54265184/is-there-one-line-syntax-for-constructing-a-struct-that-contains-a-reference-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!