[英]Rust lifetime - Book example solution
On Rust Book there's this lifetime example:在 Rust Book 上有这个生命周期示例:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
}
Simplifying this to:将其简化为:
fn main() {
let x;
{
let y = 42;
x = &y;
}
println!("The value of 'x' is {}.", x);
}
Is it possible to have it work without clone
?没有clone
可以让它工作吗?
In this example, you can simply enlarge the lifetime of y
by removing the scope introduced by the curly braces.在此示例中,您可以通过删除花括号引入的 scope 来简单地延长y
的寿命。
fn main() {
let x;
let y = 42;
x = &y;
println!("The value of 'x' is {}.", x);
}
Or, as others suggested, you can transfer the ownership from y
to x
, ie move the value from y
to x
, by removing the reference operator &
from y
:或者,正如其他人建议的那样,您可以将所有权从y
转移到x
,即将值从y
移动到x
,方法是从y
中删除引用运算符&
:
fn main() {
let x;
{
let y = 42;
x = y;
}
println!("The value of 'x' is {}.", x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.