考虑以下无效的 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
。有没有一种简单的方法可以一次性解决这个问题?
不,除了您输入的语法之外,没有这样的语法。
有关引用临时对象时其生存时间的详细信息,请参阅:
将有一个父结构体同时拥有bar
和foo
正在引用它。
祝你好运:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)