我学的是锈。作为参考,我在“锈书”第3.5章:
https://doc.rust-lang.org/book/ch03-05-control-flow.html
我写了这段代码:
fn main() {
let mut a: [i32; 5] = [10, 20, 30, 40, 50];
for (index, value) in a.iter_mut().enumerate() {
*value /= 10;
//a[index] -= 1;
println!("a[{}] : {}", index, value);
}
for index in 0..a.len() {
a[index] -= 1;
println!("a[{}] : {}", index, a[index]);
}
a[0] = 10;
println!("Len : {}", a.len());
println!("{:?}", a);
}如果取消注释行"//aindex -= 1“,我不会取消为什么;”它会生成一个错误:
error[E0503]: cannot use `a` because it was mutably borrowed
--> src/main.rs:6:9
|
4 | for (index, value) in a.iter_mut().enumerate() {
| ------------------------
| |
| borrow of `a` occurs here
| borrow later used here
5 | *value /= 10;
6 | a[index] -= 1;
| ^^^^^^^^ use of borrowed `a`
error[E0503]: cannot use `a[_]` because it was mutably borrowed
--> src/main.rs:6:9
|
4 | for (index, value) in a.iter_mut().enumerate() {
| ------------------------
| |
| borrow of `a` occurs here
| borrow later used here
5 | *value /= 10;
6 | a[index] -= 1;
| ^^^^^^^^^^^^^ use of borrowed `a`
For more information about this error, try `rustc --explain E0503`.
error: could not compile `collections` due to 2 previous errors有趣的是,之后我可以访问循环中的"aindex“。
发布于 2022-09-01 15:05:55
迭代涉及到不间断的借贷。修改涉及到可变的借用。你不能同时拥有这两者。第二个循环不是在a上迭代,而是在使用( a.len()的一个副本)构造的范围上迭代。该范围没有实际的参考向量,所以你可以安全地借用。
假设你打算除以10,然后减去1,我们可以用map来做到这一点。铁锈在处理迭代器的方式上更像功能,更喜欢关注高层操作。
let my_new_vec: Vec<_> = a.iter().map(|x| x / 10 - 1).collect();https://stackoverflow.com/questions/73571550
复制相似问题