我是Rust的新手,我很难理解一些引用/borrow 行为.
下面是一个无法编译的代码片段.我正在try 创建一个由u64
个"切片"组成的数组,我想修改它们的值,然后稍后访问:
fn main() {
// Initialize an array of "slices" with dummy data
let mut refs: [&[u64]; 4] = [&[0; 2]; 4];
// Write some computed values to the array
for i in 0..refs.len() {
// ...
// some computation to get `x` and `y`
// ...
let data: [u64; 2] = [x as u64, y as u64];
let data_ref: &[u64] = &data;
refs[i] = data_ref;
}
// Read the computed values from the array
println!("{}", refs[3][0]);
}
编译器返回:
error[E0597]: `data` does not live long enough
--> src\main.rs:8:32
|
7 | let data: [u64; 2] = [x as u64, y as u64];
| ---- binding `data` declared here
8 | let data_ref: &[u64] = &data;
| ^^^^^ borrowed value does not live long enough
9 | refs[i] = data_ref;
10 | }
| - `data` dropped here while still borrowed
...
13 | println!("{}", refs[3][0]);
| ------- borrow later used here
虽然我知道data
的作用域是在for
循环中,并且它将不再存在于for
循环之外(因此将refs[i]
设置为引用data
应该会导致编译器错误,因为refs
的生命周期 超过data
),但我不确定是否有其他方法可以正确设置refs
的值.
从这样的数组中声明、初始化然后读取"切片"值的适当("Rust ")方式是什么?