我试图创建一个泛型特征,其中一个方法使用一个默认实现,该实现包装其余方法以减少样板.
这是一个最小的复制:
trait ReadFormat<'a, 'b: 'a, Arg: 'b, T: 'static>: Sized {
fn new(c: &'a mut Cursor<'a>, arg: Arg) -> Self;
fn into_format(self) -> SResult<T>;
fn read(bytes: &'b [u8], arg: Arg) -> SResult<T> {
let c = &mut Cursor::new(bytes);
let r = Self::new(c, arg);
let f = r.into_format();
f
}
}
我收到以下错误
61 | trait ReadFormat<'a, 'b: 'a, Arg: 'b, T: 'static>: Sized {
| -- lifetime `'a` defined here
...
65 | let c = &mut Cursor::new(bytes);
| ^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
66 | let r = Self::new(c, arg);
| ----------------- argument requires that borrow lasts for `'a`
...
69 | }
| - temporary value is freed at the end of this statement
我试过各种不同的人生组合,但都不管用.总的来说,我不明白当它被into_Format消耗,而T拥有它的所有数据时,它为什么期望self在读取返回后存活.
如果我将完全相同的代码复制粘贴到一个具体的实现中,并用Reader::New替换Self::New,它就会编译.
impl<'a, 'b: 'a> ReadFormat<'a, 'b, (), ()> for Reader<'a> {
..
fn read(bytes: &'b [u8], arg: ()) -> SResult<()> {
let c = &mut Cursor::new(bytes);
let r = Reader::new(c, arg);
let f = r.into_format();
f
}
}