是否有用于构造包含对临时对象的引用的结构的单行语法?

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

考虑以下无效的 Rust 代码。有一个结构 Foo 包含对第二个结构 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);
}

编译器不喜欢这样:

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

我可以按照编译器所说的进行操作 - 使用 let 绑定:

fn main() {
    let bar = &Bar::empty();
    let foo = Foo::new(bar);
    println!("{}", foo.bar.value);
}

但是,突然间我需要两行代码来处理像实例化我的 Foo 这样微不足道的事情。有什么简单的方法可以一次性解决这个问题吗?

不,除了您输入的内容外,没有这样的语法。

有关临时文件在您引用它时可以存活多长时间的详细信息,请参阅:


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

祝你好运: