I'm getting started with Rust. The language is very interesting, but the learning curve is definitely steep . I've jumped straight in to write some code, and have had some trouble with getting it to compile.
I'm writing a parser that operates on a Vec buffer and I want to return chunks of data (the MySlice structure), each chunk being essentially a slice in the buffer. Originally the code did not require lifetime specifiers in structures, I added them to be able to describe the data: &'a [u8]
field. At this point I had the following code:
struct MyParser<'a> {
buffer: &'a Vec<u8>,
num_modifs: u32,
}
struct MySlice<'a> {
data: &'a [u8],
}
impl<'a> MyParser<'a> {
fn new(buf: &'a Vec<u8>) -> MyParser<'a> {
MyParser {
buffer: buf,
num_modifs: 0,
}
}
fn test(&mut self) -> MySlice {
let modifs = self.num_modifs;
let res = self.do_something();
self.num_modifs = modifs;
res
}
fn do_something(&mut self) -> MySlice {
self.inc_modifs();
MySlice { data: &self.buffer[0..2] }
}
fn inc_modifs(&mut self) {
self.num_modifs += 1;
}
}
And when compiling, I got the following error message:
error: cannot assign to `self.num_modifs` because it is borrowed
note: borrow of `self.num_modifs` occurs here
let res = self.do_something();
It turns out I had forgotten to specify the 'a lifetime on the result of the "do_something" and "test" methods. What I don't understand is why does the compiler tell me that I'm borrowing self.num_modifs if I don't specify the lifetime? What's going on?
EDIT: replaced the preformatted block by a code block using 3 backticks to get syntax highlighting