嵌套数据结构的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

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)