【问题标题】:Rust mutability of nested data structuresRust 嵌套数据结构的可变性
【发布时间】:2020-09-07 04:48:03
【问题描述】:

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

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

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

【问题讨论】:

标签: vector rust mutable


【解决方案1】:

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

【讨论】:

  • 补充:借用检查器能够在结构级别执行部分借用,但函数对借用检查器是不透明的。借用检查器可以看穿对inner.vectoir 和inner.blah 的访问,并理解它们不重叠,但它无法看穿set_blah,因此它担心aways 借用了整个结构。跨度>
  • 另外,@Masklinn 所说的是故意的,而不是借用检查器的技术限制。它允许基于它的 签名 而不是它的内容(可能在另一个 crate 中)来推理(和向后兼容性保证)像 set_blah() 这样的方法。
猜你喜欢
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2020-01-31
  • 2014-04-27
  • 2018-03-16
  • 2021-05-19
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多