lifetime mismatch - 返回引用的可变变量

时间:2018-05-08 14:05:13

标签: reference rust immutability lifetime

我有不同形状的结构:

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

1 个答案:

答案 0 :(得分:1)

修复代码并不容易,因为有大量缺失的内容,但您可能希望使用显式生命周期重新定义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. 作为参考的每个参数都有自己的生命周期参数。换句话说,具有一个参数的函数获得一个生命周期   参数:fn foo<'a>(x: &'a i32)具有两个参数的函数   两个单独的生命周期参数fn foo<'a, 'b>(x: &'a i32, y: &'b i32),依此类推。

  2.   
  3. (...)

  4.   
  5. 如果有多个输入生命周期参数,但其中一个是&self&mut self,因为这是一种方法,那么自我的生命周期   被分配给所有输出生命周期参数。 (...)

  6.