怎么理解Rust Borrow Rule?
Here’s the rules about borrowing in Rust:
First, any borrow must last for a smaller scope than the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time:
- 0 to N references (&T) to a resource.
- exactly one mutable reference(&mut T)
You may notice that this is very similar, though not exactly the same as, to the definition of a data race:
There is a ‘data race’ when two or more pointers access the same
memory location at the same time, where at least one of them is
writing, and the operations are not synchronized.
With references, you may have as many as you’d like, since none of them are writing. If you are writing, you need two or more pointers to the same memory, and you can only have one &mut at a time. This is how Rust prevents data races at compile time: we’ll get errors if we break the rules.
With this in mind, let’s consider our example again.
这段话到底是什么意思?
Answers
-
0 to N references (&T) to a resource.
一个引用(可变或者不可变的)可以有0或任意多个不可变引用(&T),就像这样
let a = Box::new(10);
// 或者
// let mut a = Box::new(10);
let b = &a;
let C = &a;
.......
-
exactly one mutable reference(&mut T)
只能存在一个可变引用
let mut x = 5;
let y = &mut x;
let z = &mut x;
就会报错:
main.rs:4:18: 4:19 error: cannot borrow
x
as mutable more than once at a time
对于一个变量,不能存在多个&mut引用。
目的就是为了避免并发时的数据竞争,但有一点需要注意:
let mut a = Box::new(10);
let b = &a;
let c = &mut a;
就会报如下错误
error: cannot borrow
a
as mutable because it is also borrowed as immutable
&T和&mut T是不能同时使用的, 无论先后顺序,下面的代码一样是错的:
let mut a = Box::new(10);
let b = &mut a;
let c = &a;
编译器就是依靠这样的机制在编译期发现很多问题,避免运行时出错。
写的有点匆忙,有问题再问吧