分配给借入变量如何违反引用规则? [英] How does assigning to a borrowed variable violate the rules of references?
本文介绍了分配给借入变量如何违反引用规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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
Rust书只有两个规则:
The Rust book has only two rules:
- 对资源的一个或多个引用(
& T
), - 恰好是一个可变引用(
& mut T
)。
- 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?
推荐答案
- 在任何给定时间,您都可以具有一个可变引用或任意数量的不可变引用。
- 引用必须始终有效。
隐式重新分配变量需要可变的引用:
Reassigning a variable implicitly requires a mutable reference:
fn main() {
let mut x = 33;
let link = &x;
x = 22;
*(&mut x) = 22; // Basically the same thing
}
重要的是,重新分配了变量 mutates 变量,该变量将导致不可变引用链接
的值发生更改,这是不允许的。
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:
fn main() {
let x;
// Some other code
x = 42;
}
这篇关于分配给借入变量如何违反引用规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文