首页 > 解决方案 > Rust 嵌套数据结构的可变性

问题描述

谁能解释为什么下面的代码会编译,但是如果我注释掉一行,那么即使代码本质上是做同样的事情,它也不会?

struct OtherStruct {
  x: i32,
}

struct Inner {
  blah: i32,
  vector: Vec<OtherStruct>
}

struct Outer {
  inner: Inner,
}

impl Inner {
  pub fn set_blah(&mut self, new_val : i32) {
    self.blah = new_val;
  }
}

fn main() {
  let mut outer = Outer {
    inner: Inner {
      blah: 10,
      vector: vec![
        OtherStruct { x: 1 },
        OtherStruct { x: 2 },
        OtherStruct { x: 3 },
        OtherStruct { x: 4 },
        OtherStruct { x: 5 },
      ]
    }
  };

  for item in outer.inner.vector.iter() {
    println!("{}", item.x);
    outer.inner.blah = 4;
    //outer.inner.set_blah(6);
  }

}

编译器错误是:

   |
34 |   for item in outer.inner.vector.iter() {
   |               -------------------------
   |               |
   |               immutable borrow occurs here
   |               immutable borrow later used here
...
37 |     outer.inner.set_blah(6);
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

这对我来说很有意义,我想我想知道为什么当我不使用函数调用时允许我逃脱它,肯定会出现相同的可变性问题?

标签: vectorrustmutable

解决方案


set_blah需要借用整个Innerstruct 对象。赋值blah只需要借用字段本身,因为它还没有被借用。


推荐阅读