生命周期不匹配 - Return 一个引用的可变变量

lifetime mismatch - Return a referenced mutable variable

我有不同形状的结构:

struct Triangle { points: Vec<u8> }

struct Square { points: Vec<u8> }

struct Pentagon { points: Vec<u8> }

我有一个特质CursorReadWrite:

use std::io::Cursor;

pub trait CursorReadWrite {
    fn mwrite(&mut self, writer: &mut Cursor<Vec<u8>>) -> &mut Cursor<Vec<u8>>;
    fn mread(&mut self, reader: &mut Cursor<Vec<u8>>);
}

我可以为 TriangleSquare 等实现它

impl CursorReadWrite for Triangle {
    fn mwrite(&mut self, writer: &mut Cursor<Vec<u8>>) -> &mut Cursor<Vec<u8>> {
        //do some work and write the data on Cursor<>
        writer.write(somedata);
        return writer;
    }
    fn mread(&mut self, reader: &mut Cursor<Vec<u8>>) {
        //read data and do some work and save it in mutable self ( Triangle, Square etc)
        self.points = somedata;
    }
}

像这样调用函数

let csd = Cursor::new(Vec::<u8>::new());
let mut t = Triangle::default();
let new_csd = t.mwrite(&mut csd);
t.mread(&mut new_csd);

它给出了这个错误

error[E0623]: lifetime mismatch
   |
25 |     fn mwrite(&mut self,writer: &mut Cursor<Vec<u8>>) -> &mut Cursor<Vec<u8>>{
   |                                     --------------------     ----------------------------
   |                                     |
   |                                     this parameter and the return type are declared with different lifetimes...
...
28 |             return writer;
   |                    ^^^^^^^^^^^^ ...but data from `writer` is returned here

修复您的代码并不容易,因为有很多遗漏的部分,但您可能想重新定义 mwrite 具有明确的生命周期:

pub trait CursorReadWrite<'a, 'b> {
    fn mwrite(&'a mut self, writer: &'b mut Cursor<Vec<u8>>) -> &'b mut Cursor<Vec<u8>>;
    fn mwread(&mut self, reader: &mut Cursor<Vec<u8>>);
}

impl<'a, 'b> CursorReadWrite<'a, 'b> for Triangle{
    fn mwrite(&'a mut self, writer: &'b mut Cursor<Vec<u8>>) -> &'b mut Cursor<Vec<u8>>{
        ...
    }
}

当您有超过 1 个输入生命周期时,编译器无法判断您要选择哪一个作为输出。引用 lifetime elision rules:

  1. Each parameter that is a reference gets its own lifetime parameter. In other words, a function with one parameter gets one lifetime parameter: fn foo<'a>(x: &'a i32), a function with two arguments gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32), and so on.

  2. (...)

  3. If there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, then the lifetime of self is assigned to all output lifetime parameters. (...)