rust - 值引用当前函数拥有的数据
问题描述
这是我的代码:
struct Something<'a> {
val: u32,
another: &'a AnotherThing,
}
struct AnotherThing {
val: u32,
}
impl Default for AnotherThing {
fn default() -> Self {
Self {
val: 2,
}
}
}
trait Anything {
fn new(val: u32) -> Self;
}
impl Anything for Something<'_> {
fn new(val: u32) -> Self {
Self {
val,
another: &AnotherThing::default(),
}
}
}
fn main() {
let _ = Something::new(1);
}
它无法编译,因为:
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:24:9
|
24 | / Self {
25 | | val,
26 | | another: &AnotherThing::default(),
| | ----------------------- temporary value created here
27 | | }
| |_________^ returns a value referencing data owned by the current function
我理解这个问题,但我不知道如何解决它。如果在这种情况下无法使用 Default 特征,我该如何处理函数所有权。下面是一个更简单的例子:
struct Something<'a> {
val: u32,
another: &'a AnotherThing,
}
struct AnotherThing {
val: u32,
}
trait Anything {
fn new(val: u32) -> Self;
}
impl Anything for Something<'_> {
fn new(val: u32) -> Self {
let at = AnotherThing { val : 2 };
Self {
val,
another: &at,
}
}
}
fn main() {
let _ = Something::new(1);
}
如果我有another: &AnotherThing { val : 2 }
而不是another: &at
它会工作。如果我希望another
属性成为引用并从函数中获取值,我该怎么做?
解决方案
你可以这样做
#[derive(Default)]
struct Something<'a> {
val: u32,
another: &'a AnotherThing,
}
struct AnotherThing {
val: u32,
}
impl<'a> Default for &'a AnotherThing {
fn default() -> &'a AnotherThing {
&AnotherThing {
val: 3,
}
}
}
trait Anything {
fn new(val: u32) -> Self;
}
impl Anything for Something<'_> {
fn new(val: u32) -> Self {
Self {
val,
..Default::default()
}
}
}
推荐阅读
- javascript - 如何使用 joi 设置正确的模式和验证?
- c++ - 如何创建一个将学生姓名与其分数相匹配的数组?
- python - 如何将 'features="html.parser"' 添加到 BeautifulSoup 构造函数
- reactjs - 将使用 create react app 创建的 react 应用程序移动到另一台计算机
- php - 如何在html表格中显示选择框?
- java - 缓存其他实体映射的关系
- node.js - 使用 SQS 私有端点批量发送消息
- flask - 烧瓶中的 sqlalchemy.exc.OperationalError
- algorithm - 在一个数组中找到一个在线性时间内是其他任何一个数字的两倍大的数字
- sqlite - sqlite3.OperationalError:没有这样的表:page2