Rust 生命周期 - 书籍示例解决方案
Rust lifetime - Book example solution
在 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); // |
}
将其简化为:
fn main() {
let x;
{
let y = 42;
x = &y;
}
println!("The value of 'x' is {}.", x);
}
是否可以在没有 clone
的情况下使用它?
在此示例中,您可以通过删除花括号引入的范围来简单地延长 y
的生命周期。
fn main() {
let x;
let y = 42;
x = &y;
println!("The value of 'x' is {}.", x);
}
或者,正如其他人所建议的,您可以将所有权从 y
转移到 x
,即将值从 y
移到 x
,方法是删除引用来自 y
的运算符 &
:
fn main() {
let x;
{
let y = 42;
x = y;
}
println!("The value of 'x' is {}.", x);
}
在 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); // |
}
将其简化为:
fn main() {
let x;
{
let y = 42;
x = &y;
}
println!("The value of 'x' is {}.", x);
}
是否可以在没有 clone
的情况下使用它?
在此示例中,您可以通过删除花括号引入的范围来简单地延长 y
的生命周期。
fn main() {
let x;
let y = 42;
x = &y;
println!("The value of 'x' is {}.", x);
}
或者,正如其他人所建议的,您可以将所有权从 y
转移到 x
,即将值从 y
移到 x
,方法是删除引用来自 y
的运算符 &
:
fn main() {
let x;
{
let y = 42;
x = y;
}
println!("The value of 'x' is {}.", x);
}