rust - 临时值在自定义结构中的寿命不够长
问题描述
我正在尝试使用 Serde 解析带有来自 JSON 的客户结构的数组。我简化了重现问题的示例,但想法是一样的——我有带有客户结构的向量:
#[derive(Debug)]
struct X {
x: String,
y: String,
}
fn get_d<'a>() -> Vec<&'a X> {
let mut y: Vec<&X> = vec![];
let x = vec![
&X {
x: String::new(),
y: String::new(),
},
&X {
x: String::new(),
y: String::new(),
},
];
for i in x.iter() {
y.push(i);
}
y
}
fn main() {
let d = get_d();
println!("{:?}", d);
}
我得到了错误:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:10:10
|
10 | &X {
| __________^
11 | | x: String::new(),
12 | | y: String::new(),
13 | | },
| |_________^ temporary value does not live long enough
...
18 | ];
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 7:10...
--> src/main.rs:7:10
|
7 | fn get_d<'a>() -> Vec<&'a X> {
| ^^
= note: consider using a `let` binding to increase its lifetime
如果我更改String
为结构中的u16
atx
和y
字段,X
那么它可以工作。这个想法是我想从函数中返回向量的一部分,不要介意值或指针。
如果我尝试返回一个值向量,我会得到:
14 | y.push(*i);
| ^^ cannot move out of borrowed content
解决方案
推荐阅读
- python - 如何在 python 中覆盖 1/x 运算符
- matlab - 关于matlab中的泊松生成器poissrnd的问题
- discord.js - 当用户对特定消息做出反应时如何添加角色
- android - 我正在尝试从 Firebase 数据库中的“价格”节点获取值的总和
- react-bootstrap - 无法应用引导程序做出反应(类型无效)
- javascript - 如何存根从另一个函数调用的模块函数
- javascript - 尝试使用 javaScript 制作第二张图片而不是第一张图片
- java - 如何找到这个动态值?如何获取此文本(对我的操作)及其在硒中的动态值
- flutter - 在 Flutter 中处理视频通话状态
- java - 如何在 cs50 的第一个问题集中获得用户的输入?