I have a lifetime problem that I can't seem to crack. An example of my problem is here. Essentially I have a method that returns an instance of T (which I intended to always be owned) that the method creates based on the contents of a buffer.
pub fn read<'this, 'bytes, T>(&'this mut self) -> Result<T, ()>
where
T: TryFrom<&'bytes [u8], Error = ()> + 'static,
{
let buf = self.buffer.fill_buf().unwrap();
let size = buf.len();
let result = T::try_from(buf); // Compiler-error
self.buffer.consume(size);
result
}
It continues to fail with
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> test2.rs:38:31
|
38 | let buf = self.buffer.fill_buf().unwrap();
| ^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'this` as defined on the method body at 34:17...
--> test2.rs:34:17
|
34 | pub fn read<'this, 'bytes, T>(&'this mut self) -> Result<T, ()>
| ^^^^^
note: ...so that reference does not outlive borrowed content
--> test2.rs:38:19
|
38 | let buf = self.buffer.fill_buf().unwrap();
| ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'bytes` as defined on the method body at 34:24...
--> test2.rs:34:24
|
34 | pub fn read<'this, 'bytes, T>(&'this mut self) -> Result<T, ()>
| ^^^^^^
note: ...so that reference does not outlive borrowed content
--> test2.rs:40:34
|
40 | let result = T::try_from(buf); // Compiler-error
| ^^^
Now that make sense if a T actually holds a reference to buf but my intention is that T should always be owned (and this works if I hard code an owned type in place of T). I attempted to communicate this to the compiler by adding the 'static lifetime bound but that doesn't stop a T from containing references, it only ensures that those reference are 'static, which of course the reference to buf will not satisfy.
So is there a bound I can place on T to ensure that it is always owned (never holds a reference to the buf)? Or is there some better way to structure this code?
Thanks in advance!