如果我有一个封装两个成员的结构,并基于另一个更新一个,那么只要我这样做就可以了:
struct A {
value: i64
}
impl A {
pub fn new() -> Self {
A { value: 0 }
}
pub fn do_something(&mut self, other: &B) {
self.value += other.value;
}
pub fn value(&self) -> i64 {
self.value
}
}
struct B {
pub value: i64
}
struct State {
a: A,
b: B
}
impl State {
pub fn new() -> Self {
State {
a: A::new(),
b: B { value: 1 }
}
}
pub fn do_stuff(&mut self) -> i64 {
self.a.do_something(&self.b);
self.a.value()
}
pub fn get_b(&self) -> &B {
&self.b
}
}
fn main() {
let mut state = State::new();
println!("{}", state.do_stuff());
}
也就是说,当我直接引用self.b
. 但是当我改变do_stuff()
这个:
pub fn do_stuff(&mut self) -> i64 {
self.a.do_something(self.get_b());
self.a.value()
}
编译器抱怨:cannot borrow `*self` as immutable because `self.a` is also borrowed as mutable
.
如果我需要做一些比返回成员更复杂的事情来获取参数a.do_something()
怎么办?我必须创建一个b
按值返回的函数并将其存储在绑定中,然后将该绑定传递给do_something()
?如果b
复杂怎么办?
根据我的理解,更重要的是,编译器从这里救了我什么样的内存不安全?