[英]Rust - Why does dereferencing and borrowing break borrowing rules?
As per my understanding, there can be multiple immutable references at a time but if there is a mutable reference it can be the only usable reference.根据我的理解,一次可以有多个不可变引用,但如果有一个可变引用,它可能是唯一可用的引用。
Why does the following code work?:为什么以下代码有效?:
fn main() {
let mut y = String::from("bar");
let f: &mut String = &mut y;
let f2: &String = &(*f);
// not allowed since mutable reference already exists
// let f3: &String = &y;
println!("{}, ", f.as_str());
println!("{}", f2.as_str());
}
Edit: Another part of my question which I guess isn't obvious is: why am I not allowed to create f3
(like I am doing in the commented line) when it is exactly the same thing as f2
and created similarly by refrencing y
.编辑:我想我的问题的另一部分并不明显是:为什么我不允许创建
f3
(就像我在评论行中所做的那样),当它与f2
完全相同并且通过引用y
类似地创建时。
Because the compiler is smart enough to know if the data actually is used as mutable before it is used as immutable.因为编译器足够聪明,可以在数据用作不可变之前知道数据是否实际用作可变数据。 If you change the code at all to use the mutable reference first, it fails.
如果您完全更改代码以首先使用可变引用,它将失败。
fn main() {
let mut y = String::from("bar");
let f: &mut String = &mut y;
let f2: &String = &(*f);
f.clear();
// not allowed since mutable reference already exists
// let f3: &String = &y;
println!("{}, ", f.as_str());
println!("{}", f2.as_str());
}
Here's a link to a live example .这是一个现场示例的链接。 The error, as you'd expect, mentions you cannot have an immutable reference if a mutable one exists.
如您所料,该错误提到如果存在可变引用,则不能拥有不可变引用。
error[E0502]: cannot borrow `*f` as mutable because it is also borrowed as immutable
--> src/main.rs:6:5
|
5 | let f2: &String = &(*f);
| ----- immutable borrow occurs here
6 | f.clear();
| ^^^^^^^^^ mutable borrow occurs here
...
12 | println!("{}", f2.as_str());
| ----------- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` due to previous error
In short, you can only have one borrow if you have a mutable reference, but the compiler is intelligent enough to know when the value cannot change: in your example, f
cannot change when it is used before f2
is used, so it knows it doesn't change.简而言之,如果你有一个可变引用,你只能借一个,但是编译器足够聪明,知道什么时候值不能改变:在你的例子中,在使用
f2
之前使用f
时不能改变,所以它知道没有改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.