这里发生了什么(游乐场)?
struct Number {
num: i32
}
impl Number {
fn set(&mut self, new_num: i32) {
self.num = new_num;
}
fn get(&self) -> i32 {
self.num
}
}
fn main() {
let mut n = Number{ num: 0 };
n.set(n.get() + 1);
}
Run Code Online (Sandbox Code Playgroud)
给出了这个错误:
error[E0502]: cannot borrow `n` as immutable because it is also borrowed as mutable
--> <anon>:17:11
|
17 | n.set(n.get() + 1);
| - ^ - mutable borrow ends here
| | |
| | …Run Code Online (Sandbox Code Playgroud) 在下面的代码示例中,我试图以四种不同的方式通过a对结构X的可变引用来增加结构的成员变量。在这里,编译器为由 表示的行给出以下错误B:
error[E0502]: cannot borrow `*x` as immutable because it is also borrowed as mutable
--> src\main.rs:17:23
|
17 | *x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
| ------------------^--------
| || |
| || immutable borrow occurs here
| |mutable borrow occurs here
| mutable borrow later used here
Run Code Online (Sandbox Code Playgroud)
如果是使用可变和不可变的参照问题a在同一个表达式,为什么C和D编译?
struct X {
a: i64,
}
impl X {
pub fn get_a_mut(&mut self) -> &mut i64 {
return &mut …Run Code Online (Sandbox Code Playgroud)