对于我的程序,我想用包含整数的数组填充一个向量,但在某些时候,我可能想要操作向量中的最后一个条目(如果存在)。我的目标是尽可能高效地执行此操作。所以我想按以下方式进行。我试图更改代码并使其运行,但到目前为止我失败了。我希望有人能帮助我,所以我提供了一个我用来理解问题的最小示例。
fn main() {
let mut test_vec: Vec<[i8; 3]> = vec![];
test_vec.push([1, 2, 3]);
test_vec.push([4, 5, 6]);
match test_vec.last() {
Some(v) => {
v[2] = 0; // this does not work <= need help!
}
None => {}
}
test_vec.push([7, 8, 9]);
match test_vec.last() {
Some(v) => {
v[1] = 0; // this also fails <= need help!
}
None => {}
}
for entry in test_vec {
println!("{entry:?}"); // should print [1, 2, 3], [4, 5, 0] and [7, 0, 9]
}
}
[T]::last
返回Option<&T>
。这是共享引用,不能用于修改指向的数据。使用[T]::last_mut
,返回Option<&mut T>
。&[...]
请注意,Rust 编译器会尝试通过告诉您将绑定从 更改为来建议此解决方案&mut [...]
。