上一节看到,把 String 传给函数会转移所有权。如果函数只是想读取一下字符串,这种做法很不方便:
fn main() { let s = String::from("hello"); let len = calculate_length(s); // s 的所有权被移动 // println!("{}", s); // 错误:s 不再有效 println!("The length is {}", len); } fn calculate_length(s: String) -> usize { s.len() }
为了让函数使用但不获取所有权,Rust 引入了引用(reference):
fn main() { let s = String::from("hello"); let len = calculate_length(&s); // 把 s 的引用传过去 println!("The length of '{}' is {}.", s, len); // s 仍然有效 } fn calculate_length(s: &String) -> usize { s.len() } // s 是引用,不拥有值,离开作用域时不会释放内存
这种把引用作为函数参数的行为叫做借用(borrowing)。
默认情况下,引用是不可变的:
fn main() { let s = String::from("hello"); change(&s); } fn change(s: &String) { // s.push_str(", world"); // 错误:无法通过不可变引用修改数据 }
不可变引用允许多人读取,但不允许修改。
如果需要修改借用的数据,必须使用可变引用:
fn main() { let mut s = String::from("hello"); change(&mut s); println!("{}", s); } fn change(s: &mut String) { s.push_str(", world"); }
注意:
- 原变量必须是 mut 的。
- 引用也必须是 &mut。
- 在可变引用有效期内,不能存在其他引用(可变或不可变)。
Rust 编译器强制以下两条核心规则:
fn main() { let s = String::from("hello"); let r1 = &s; let r2 = &s; println!("{} and {}", r1, r2); }
fn main() { let mut s = String::from("hello"); let r1 = &s; let r2 = &s; // let r3 = &mut s; // 错误:不能在有不可变引用时创建可变引用 println!("{} and {}", r1, r2); }
编译器使用非词法作用域生命周期(NLL) 来判断引用实际用到哪里。只要不可变引用不再被使用,就可以创建可变引用:
fn main() { let mut s = String::from("hello"); let r1 = &s; let r2 = &s; println!("{} and {}", r1, r2); // r1 和 r2 最后一次使用 let r3 = &mut s; // 从这里开始,r1 和 r2 不再被使用,所以可以创建可变引用 println!("{}", r3); }
悬垂引用是指引用指向的内存已经被释放:
fn main() { let reference_to_nothing = dangle(); } fn dangle() -> &String { let s = String::from("hello"); &s // 错误:返回局部变量的引用 } // s 在这里被释放,返回的引用指向无效内存
Rust 编译器会拒绝这段代码。正确的做法是返回 String 本身,转移所有权:
fn no_dangle() -> String { let s = String::from("hello"); s }
使用 * 可以获取引用指向的值:
fn main() { let x = 5; let y = &x; assert_eq!(5, x); assert_eq!(5, *y); // 解引用 y }
对于实现了 Deref trait 的类型,Rust 会自动处理很多场景,这部分会在进阶课程中讲解。
| 引用类型 | 语法 | 能否修改 | 数量限制 |
| 不可变引用 | &T | 否 | 任意多个 |
| 可变引用 | &mut T | 是 | 同一作用域只能有一个,且不能与不可变引用共存 |
rust
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(s: &String) {
s.push_str(", world");
}