rust - Rust 生命周期 - 书籍示例解决方案
问题描述
在 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);
}
推荐阅读
- java - 如何使用 ShadowJar 创建 Jar 文件
- javascript - 我无法拼接数组 - × TypeError: Cannot read property 'splice' of undefined
- javascript - 如何在 React 中映射对象值?
- bash - 如何使用 bcftools 视图根据深度过滤我的 vcf 文件?
- reactjs - React 中网格、样式组件和排版的移动响应能力?
- julia - Julia中的上采样复杂矩阵
- python-3.x - Holoviews 热图动画标签滑块
- oop - 一种会议日历系统的数据结构设计
- html - “溢出:隐藏”不会在 Iphone 上隐藏孩子
- c# - C# 获取调用另一个方法的方法的名称