首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能在for循环中使用对集合的引用?

为什么我不能在for循环中使用对集合的引用?
EN

Stack Overflow用户
提问于 2022-09-01 15:01:18
回答 1查看 74关注 0票数 0

我学的是锈。作为参考,我在“锈书”第3.5章:

https://doc.rust-lang.org/book/ch03-05-control-flow.html

我写了这段代码:

代码语言:javascript
复制
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“,我不会取消为什么;”它会生成一个错误:

代码语言:javascript
复制
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“。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-01 15:05:55

迭代涉及到不间断的借贷。修改涉及到可变的借用。你不能同时拥有这两者。第二个循环不是在a上迭代,而是在使用( a.len()的一个副本)构造的范围上迭代。该范围没有实际的参考向量,所以你可以安全地借用。

假设你打算除以10,然后减去1,我们可以用map来做到这一点。铁锈在处理迭代器的方式上更像功能,更喜欢关注高层操作。

代码语言:javascript
复制
let my_new_vec: Vec<_> = a.iter().map(|x| x / 10 - 1).collect();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73571550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档