这是我的代码。最初的问题有更大的代码,但最终我将其压缩到下一个:
struct Data<'a> {
f: [&'a mut [u8]; 2],
}
impl Data<'_> {
fn new() -> Self {
let p = Self {
f: [&mut [1u8, 2u8], &mut [3u8, 4u8, 5u8]],
};
p.f[0][1] = 5;
p.f[1][2] = 7;
p
}
}
fn main() {
let v: Data = Data::new();
println!("{:?}", v.f);
}
我不知道如何让“p”变量保持活动状态!它死得太早了。另外,我不能将生命参数放入数组中(在 mut 之前),表达式不排除生命参数。我无法将生命参数放入Self中,这会导致错误。
您从编译器获得的错误消息解释了问题所在:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:8:22
|
6 | fn new() -> Self {
| ---- return type is Data<'1>
7 | let p = Self {
8 | f: [&mut [1u8, 2u8], &mut [3u8, 4u8, 5u8]],
| ------^^^^^^^^^^-----------------------
| | |
| | creates a temporary value which is freed while still in use
| this usage requires that borrow lasts for `'1`
...
13 | }
| - temporary value is freed at the end of this statement
数组,例如
[1u8, 2u8]
,是拥有的数据。创建这样的数组并返回它们就可以了。但是,对这些数组(即切片)的(可变)引用不是您可以从函数返回的内容。这是因为数组的所有者是 new
函数中的临时变量,在该函数之外无法访问该变量。
假设您想返回一个包含两个整数数组的结构,每个整数数组都是“任意”长度,您应该使用向量(也允许调整大小):
struct Data {
f: [Vec<u8>; 2],
}
impl Data {
fn new() -> Self {
let mut p = Self {
f: [vec![1u8, 2u8], vec![3u8, 4u8, 5u8]],
};
p.f[0][1] = 5;
p.f[1][2] = 7;
p
}
}
或者一个盒子:
struct Data {
f: [Box<[u8]>; 2],
}
impl Data {
fn new() -> Self {
let mut p = Self {
f: [Box::new([1u8, 2u8]), Box::new([3u8, 4u8, 5u8])],
};
p.f[0][1] = 5;
p.f[1][2] = 7;
p
}
}