I have this code:
struct Foo<'a> {
link: &'a i32,
}
fn main() {
let mut x = 33;
println!("x:{}", x);
let ff = Foo { link: &x };
x = 22;
}
Which generates this compiler error:
error[E0506]: cannot assign to `x` because it is borrowed
--> src/main.rs:9:5
|
8 | let ff = Foo { link: &x };
| - borrow of `x` occurs here
9 | x = 22;
| ^^^^^^ assignment to borrowed `x` occurs here
The Rust book has only two rules:
- one or more references (
&T
) to a resource, - exactly one mutable reference (
&mut T
).
I have one mutable variable and one immutable link. Why does the compiler give an error?
The Rust Programming Language defines the rules of references:
Reassigning a variable implicitly requires a mutable reference:
Importantly, reassigning a variable mutates the variable, which would cause the value of the immutable reference
link
to change, which is disallowed.Note that the initial assignment of the variable does not require the variable to be mutable: