为什么将字段从'&'a [u8]`更改为`&'a mut [u8]`会导致生命周期错误?

时间:2019-09-08 18:20:44

标签: rust

此代码编译:

struct BufRef<'a> {
    buf: &'a [u8],
}

struct Foo<'a> {
    buf_ref: BufRef<'a>,
}

impl<'a> Iterator for Foo<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let result = &self.buf_ref.buf;
        Some(result)
    }
}

但是,如果我将BufRef更改为:

struct BufRef<'a> {
    buf: &'a mut [u8],
}

编译器说:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src\main.rs:13:16
   |
13 |         let result = &self.buf_ref.buf;
   |                      ^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 12:5...
  --> src\main.rs:12:5
   |
12 | /     fn next(&mut self) -> Option<Self::Item> {
13 | |         let result = &self.buf_ref.buf;
14 | |         Some(result)
15 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src\main.rs:13:16
   |
13 |         let result = &self.buf_ref.buf;
   |                      ^^^^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 9:6...
  --> src\main.rs:9:6
   |
9  | impl<'a> Iterator for Foo<'a> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator

为什么将字段更改为&'a mut [u8]会导致错误?

此外,编译器的含义是什么:

...so that the types are compatible:
               expected std::iter::Iterator
                  found std::iter::Iterator

1 个答案:

答案 0 :(得分:2)

我认为误导您的是您的代码具有折叠的引用。

您的next函数基本上等效于以下代码:

fn next(&mut self) -> Option<&'a [u8]> {
    let result: &&'a [u8] = &self.buf_ref.buf;
    Some(result)
}

之所以有效,是因为双引用折叠为单个引用。在这种情况下,双重引用只会混淆代码。只需写:

fn next(&mut self) -> Option<Self::Item> {
    Some(self.buf_ref.buf)
}

这可行,因为引用始终为Copy

但是,现在将定义更改为&'a mut时会发生什么?您现在可能正在猜测...可变引用不是 Copy,因此相同的简单代码将为您提供易于理解的错误消息:

  

无法从可变引用后面的self.buf_ref.buf中移出

自然地,您可以将可变的ref作为const借入,然后尝试返回它,但不幸的是,这将不起作用,因为重新借用不能使用与可变变量相同的生存期,因此必须严格更小(或者您可以将指向的值作为别名)。编译器将此重新借用的生存期分配为next函数的生存期,但是现在您无法返回此借用,因为它是本地引用!

不幸的是,我不知道任何安全的方法来编译您的代码。实际上,我非常确定它将创建一个不完善的API。也就是说,如果您设法编译了代码,则此安全代码将创建未定义的行为:

fn main() {
    let mut buf = vec![1,2,3];
    let buf_ref = BufRef { buf: &mut buf };
    let mut foo = Foo { buf_ref };
    let x: &[u8] = foo.next().unwrap();
    //note that x's lifetime is that of buf, foo is not borrowed
    //x and foo.buf_ref.buf alias the same memory!
    //but the latter is mutable    
    println!("{}", x[0]); //prints 1
    foo.buf_ref.buf[0] = 4;
    println!("{}", x[0]); //prints what?
}