【发布时间】:2019-11-19 03:47:01
【问题描述】:
我有一个Vec<Vec<T>>(我知道这并不理想;它来自图书馆)。我想查看外部 vec 中的 Vecs 对并推送到它们中的每一个,如下所示:
let mut foo = vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for i in foo.len() {
let a = foo.get_mut(i - 1).unwrap();
let b = foo.get_mut(i).unwrap(); // Does not work
let val = 2; // Some computation based on contents of a & b
a.push(val);
b.insert(0, val);
}
当然,这样编译失败:
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> foo.rs:6:17
|
5 | let a = foo.get_mut(i - 1).unwrap();
| --- first mutable borrow occurs here
6 | let b = foo.get_mut(i).unwrap(); // Does not work
| ^^^ second mutable borrow occurs here
...
10 | a.push(val);
| - first borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0499`.
这与std::slice::window() 方法的模式相似,但据我所知,您无法在其中获得任何可变项。
有没有办法让借阅检查员高兴?
【问题讨论】:
标签: rust