2.9.3 永久借用
译文 · 基于 Learning Rust
永久借用
原文链接: https://quinedot.github.io/rust-learning/pf-borrow-forever.html
你可能遇到的一种反模式是创建 &'a mut Thing<'a>。这是一种反模式,因为它翻译为"在 Thing<'a> 的整个剩余有效期('a)内对其取独占引用"。一旦你创建了独占借用,你就不能再使用 Thing<'a>,只能通过那个借用来使用。
你不能对它调用方法,不能再次引用它,不能移动它,不能打印它,完全不能使用它。你甚至不能调用非平凡的析构函数;如果你有非平凡的析构函数,在存在 &'a mut Thing<'a> 的情况下你的代码将无法编译。
所以避免 &'a mut Thing<'a>。
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| #[derive(Debug)]
struct Node<'a>(&'a str);
fn example_1<'a>(node: &'a mut Node<'a>) {}
struct DroppingNode<'a>(&'a str);
impl Drop for DroppingNode<'_> { fn drop(&mut self) {} }
fn example_2<'a>(node: &'a mut DroppingNode<'a>) {}
fn main() {
let local = String::new();
let mut node_a = Node(&local);
// 你可以这样做一次,没问题……
example_1(&mut node_a);
let mut node_b = Node(&local);
// ……但之后你就不能再直接使用该节点了
example_1(&mut node_b);
println!("{node_b:?}");
let mut node_c = DroppingNode(&local);
// 而这个完全不行
example_2(&mut node_c);
}
|
我们稍后会看看这种模式(&'a Thing<'a>)的共享版本在后面讨论。