详解不可变引用 (&T) 与可变引用 (&mut T)。借用检查器如何在编译期彻底扑灭悬垂指针与多线程竞态条件。
1. 借用黄金法则 (The Rules of References)
在任何给定的时间,对于同一块数据:
- 要么只能有 一个可变引用 (
&mut T); - 要么可以有 任意多个不可变引用 (
&T); - 引用必须总是有效的(编译器严禁悬垂引用 Dangling Reference)。
fn main() {
let mut s = String::from("hello");
let r1 = &s; // 不可变借用
let r2 = &s; // 不可变借用
println!("{} and {}", r1, r2);
// r1, r2 作用域在此结束 (NLL: Non-Lexical Lifetimes)
let r3 = &mut s; // 可变借用,安全!
r3.push_str(", world");
}