vector - 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
这对我来说很有意义,我想我想知道为什么当我不使用函数调用时允许我逃脱它,肯定会出现相同的可变性问题?
解决方案
set_blah
需要借用整个Inner
struct 对象。赋值blah
只需要借用字段本身,因为它还没有被借用。
推荐阅读
- go - go/kubernetes - runtime.notRegisteredErr
- python - 如何使用 cron 作业将事件插入谷歌日历?
- oracle - 在 Liquibase 中,如何向现有复合主键添加新列/字段
- python - 插入顺序模型层失败
- java - ANTLR4 在访客不工作时调用下一步
- javascript - 如何将计数传递给动态 json 对象
- google-apps-script - 获取所有选项卡的列表并排除活动用户无法编辑的选项卡
- asp.net-mvc - ASP.NET Core 3.1 MVC 返回 AmbiguousMatchException,服务器错误 500
- c - 当 K&R 第 6 章中的 strdup() 没有分配 sizeof(char) * strlen(s) 位时,它是如何工作的?
- java - java中魔方中的完整缺失元素