I am trying to extract data using TryFrom, where there is a header, data, and footer. However, I am fighting with lifetimes.
My gist of this code. Confusing Borrow Behavior · GitHub
It is a simplified version of what I am trying to do.
The basic idea is a generalized struct that wraps the data extraction.
struct MyData<T>(String, T, String);
impl <'a, 'b, T> TryFrom<&'a mut DataReader<'b>> for MyData<T>
where
T: TryFrom<&'a mut DataReader<'b>>,
T::Error: From<ErrorKind>,
{
type Error = T::Error;
fn try_from(r: &'a mut DataReader<'b>) -> Result<Self, Self::Error> {
let a = String::try_from(r.as_mut())?;
let b = T::try_from(r.as_mut())?;
let c = String::try_from(r.as_mut())?;
Ok(MyData(a, b, c))
}
}
The Compile error
Compiling test_borrow v0.1.0 (/root/Projects/test_borrow)
error[E0499]: cannot borrow `*r` as mutable more than once at a time
--> src/main.rs:56:34
|
47 | impl <'a, 'b, T> TryFrom<&'a mut DataReader<'b>> for MyData<T>
| -- lifetime `'a` defined here
...
55 | let b = T::try_from(r.as_mut())?;
| ----------
| |
| first mutable borrow occurs here
| argument requires that `*r` is borrowed for `'a`
56 | let c = String::try_from(r.as_mut())?;
| ^^^^^^^^^^ second mutable borrow occurs here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `test_borrow` (bin "test_borrow" test) due to previous error