我有这个代码:
struct Foo<'a> {
link: &'a i32,
}
fn main() {
let mut x = 33;
println!("x:{}", x);
let ff = Foo { link: &x };
x = 22;
}
这会产生此编译器错误:
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
Rust 书只有两条规则:
- 一个或多个对资源的引用 (
&T
), - 正是一个可变引用 (
&mut T
)。
我有一个可变变量和一个不可变链接。为什么编译器会报错?