I want to keep binary data in Struct(e.g., aout) and refer it partially using Slice(e.g., data)
In the followings, I created a slice in test2 method and it might be succeeded.
However, as show in the next block, I cannot invoke t.test3()
I don't understand what it happens and how to realize my purpose (I am not sure it can be or not). The one thing that I know this reason is lifetime parameter('a). But I think it is necessary because I have a slice inside a structure (e.g., Test)
struct Test<'a> {
test: String,
aout: Vec<u8>,
data: &'a [u8],
}
impl<'a> Test<'a> {
fn test2(&'a mut self) {
self.data = &self.aout[0..3]; // make a slice there
println!("test2");
}
fn test3(&self) {
println!("test3");
}
}
fn main() {
println!("hoge123");
let mut t = Test{
test: String::from("abc"),
aout: vec![1,2,3,4,5],
data: &[],
};
t.test2();
t.test3(); // **--> compile error**
}
error[E0502]: cannot borrow `t` as immutable because it is also borrowed as mutable
--> examples/1.rs:31:5
|
30 | t.test2();
| --------- mutable borrow occurs here
31 | t.test3();
| ^^^^^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
When I remove lifetime parameter and slice, we can invoke:
t.test2();
t.test3();
So, the reason is lifetime but I don't know why.