面试题答案
一键面试原因
Rust遵循所有权和借用规则,其核心目标是在编译时确保内存安全,避免数据竞争。可变引用允许修改数据,而不可变引用只允许读取数据。如果同时存在一个可变引用和多个不可变引用,可能会导致数据竞争,因为可变引用可能在不可变引用读取数据时修改数据。
举例及错误信息
fn main() {
let mut num = 5;
let ref1 = #
let ref2 = #
let mut_ref = &mut num; // 错误:不能同时存在可变引用和不可变引用
println!("ref1: {}, ref2: {}", ref1, ref2);
*mut_ref = 6;
}
编译器会给出类似如下错误信息:
error[E0502]: cannot borrow `num` as mutable because it is also borrowed as immutable
--> src/main.rs:6:18
|
4 | let ref1 = #
| --- immutable borrow occurs here
5 | let ref2 = #
| --- immutable borrow occurs here
6 | let mut_ref = &mut num;
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("ref1: {}, ref2: {}", ref1, ref2);
| ---- immutable borrow later used here
修改方式
- 分开作用域:
fn main() {
let mut num = 5;
{
let ref1 = #
let ref2 = #
println!("ref1: {}, ref2: {}", ref1, ref2);
}
{
let mut_ref = &mut num;
*mut_ref = 6;
}
}
- 先修改,再读取:
fn main() {
let mut num = 5;
let mut_ref = &mut num;
*mut_ref = 6;
let ref1 = #
let ref2 = #
println!("ref1: {}, ref2: {}", ref1, ref2);
}
通过这两种方式,可以确保在任何时刻,要么只有可变引用(没有不可变引用),要么只有不可变引用(没有可变引用),从而避免数据竞争。