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.
这段话到底是什么意思?
0 to N references (&T) to a resource.
一个引用(可变或者不可变的)可以有0或任意多个不可变引用(&T),就像这样
exactly one mutable reference(&mut T)
只能存在一个可变引用
就会报错:
对于一个变量,不能存在多个&mut引用。
目的就是为了避免并发时的数据竞争,但有一点需要注意:
就会报如下错误
&T和&mut T是不能同时使用的, 无论先后顺序,下面的代码一样是错的:
编译器就是依靠这样的机制在编译期发现很多问题,避免运行时出错。
以前的一篇文章
写的有点匆忙,有问题再问吧