生命周期的局限

让我们来看以下代码:

  1. #[derive(Debug)]
  2. struct Foo;
  3. impl Foo {
  4. fn mutate_and_share(&mut self) -> &Self { &*self }
  5. fn share(&self) {}
  6. }
  7. fn main() {
  8. let mut foo = Foo;
  9. let loan = foo.mutate_and_share();
  10. foo.share();
  11. println!("{:?}", loan);
  12. }

人们可能期望它能被编译成功,我们调用mutate_and_share,它可以暂时可变借用foo,但随后只返回一个共享引用。因此我们期望foo.share()能够成功,因为foo不应该被可变借用。

然而,当我们试图编译它时:

  1. error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
  2. --> src/main.rs:12:5
  3. |
  4. 11 | let loan = foo.mutate_and_share();
  5. | --- mutable borrow occurs here
  6. 12 | foo.share();
  7. | ^^^ immutable borrow occurs here
  8. 13 | println!("{:?}", loan);

这是为啥?好吧,我们得到的推理和上一节例 2完全一样。我们对程序进行解语法糖后,可以得到如下结果:

  1. struct Foo;
  2. impl Foo {
  3. fn mutate_and_share<'a>(&'a mut self) -> &'a Self { &'a *self }
  4. fn share<'a>(&'a self) {}
  5. }
  6. fn main() {
  7. 'b: {
  8. let mut foo: Foo = Foo;
  9. 'c: {
  10. let loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo);
  11. 'd: {
  12. Foo::share::<'d>(&'d foo);
  13. }
  14. println!("{:?}", loan);
  15. }
  16. }
  17. }

由于loan的生命周期和mutate_and_share的签名,生命周期系统被迫将&mut foo扩展为'c的生命周期。然后当我们试图调用share时,它看到我们试图别名&'c mut foo,然后就炸了!

根据我们真正关心的引用语义,这个程序显然是正确的,但是生命周期系统太蠢了(原话是粗糙),无法处理这个问题。

不正确地缩减借用

下面的代码无法编译成功,因为 Rust 发现map变量被借用了两次,并且不能推断出在第二次借用之前,第一次借用已经不需要了,所以保守地退回到使用整个作用域作为第一次借用的生命周期。不过不用担心,这个问题最终会得到解决:

  1. # use std::collections::HashMap;
  2. # use std::hash::Hash;
  3. fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
  4. where
  5. K: Clone + Eq + Hash,
  6. V: Default,
  7. {
  8. match map.get_mut(&key) {
  9. Some(value) => value,
  10. None => {
  11. map.insert(key.clone(), V::default());
  12. map.get_mut(&key).unwrap()
  13. }
  14. }
  15. }

由于所施加的生命周期限制,&mut map的生命周期与其他可变的借用重叠,导致编译错误:

  1. error[E0499]: cannot borrow `*map` as mutable more than once at a time
  2. --> src/main.rs:12:13
  3. |
  4. 4 | fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
  5. | -- lifetime `'m` defined here
  6. ...
  7. 9 | match map.get_mut(&key) {
  8. | - --- first mutable borrow occurs here
  9. | _____|
  10. | |
  11. 10 | | Some(value) => value,
  12. 11 | | None => {
  13. 12 | | map.insert(key.clone(), V::default());
  14. | | ^^^ second mutable borrow occurs here
  15. 13 | | map.get_mut(&key).unwrap()
  16. 14 | | }
  17. 15 | | }
  18. | |_____- returning this value requires that `*map` is borrowed for `'m`