Rust书在References and borrowing中声明以下内容
但是所有者可以读取数据,而另一个线程通过可变借位来更改值,对吗?难道我们就不会再遇到通常的问题了吗?或者我在哪里误解了基本概念?
最佳答案
这是不正确的,甚至是否涉及多个线程也没有关系。
在下面的示例(Playground)中,您可以自己看到。这是在保留对相同值x
的引用的同时修改的字符串值y
:
let mut x = "123".to_string();
let y = &mut x;
x.push_str("456");
println!("y = {}", y);
无法编译:
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> src/main.rs:5:5
|
3 | let y = &mut x;
| ------ first mutable borrow occurs here
4 |
5 | x.push_str("456");
| ^ second mutable borrow occurs here
6 |
7 | println!("y = {}", y);
| - first borrow later used here
当我们尝试调用
push_str
时,该方法会接收到&mut self
,并且假定会在现场建立对该值的新可变引用。由于x
已在该范围内借用,因此这是非法的。现在,您甚至可以考虑重新分配,而不是调用期望
&mut self
的方法。仍然有机会:let mut x = "123".to_string();
let y = &mut x;
x = "321".to_string();
println!("y = {}", y);
error[E0506]: cannot assign to `x` because it is borrowed
--> src/main.rs:5:5
|
3 | let y = &mut x;
| ------ borrow of `x` occurs here
4 |
5 | x = "321".to_string();
| ^ assignment to borrowed `x` occurs here
6 |
7 | println!("y = {}", y);
| - borrow later used here
借用的值也不能重新分配。
总而言之,无论是哪种借贷,值(value)的所有者仍然受到限制。如果该值是一成不变地借用的,则所有者也可以具有不可变的访问权限,但是只要借入到位,就永远不能将其写入或移动该值。
当该值是可变的借入时,所有者将无法使用该值执行任何操作,直到该引用被删除为止。
关于concurrency - 当值的所有者可以在另一个线程更改它的同时读取值时,Rust如何防止数据争用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55688018/