I'm struggling with the borrow checker. I have a piece of code like this:
fn start_parser<F,R:BufRead>(reader:&mut Reader<R>,
buf:&mut Vec<u8>,
ns_buf:&mut Vec<u8>,
level:&str, mut callback: F)
where F: FnMut(&mut Reader<R>,&mut Vec<u8>, &mut Vec<u8>, &mut BytesStart)
{
loop{
let mut nse = reader.read_namespaced_event(buf, ns_buf);
match nse {
Ok((ref ns, Event::Start(ref mut e))) => {
match *ns {
Some(b"http://www.w3.org/2002/07/owl#") =>
{
callback(reader, buf, ns_buf, e);
}
Some(_) =>{
println!("{}: Unknown Element:{:?}",
level, e.local_name())
}
None => {
println!("{}: Unknown Element without ns:{:?}",
level, e.local_name());
}
}
}
Err(e) => {
println!("Error: {}", e);
},
Ok((_, Event::Eof)) => break,
_ => {
// Ignore non starts
}
}
}
}
which complains because I am borrowing twice.
error[E0499]: cannot borrow `*buf` as mutable more than once at a time
--> io_quick_port.rs:43:42
|
37 | let mut nse = reader.read_namespaced_event(buf, ns_buf);
| --- first mutable borrow occurs here
...
43 | callback(reader, buf, ns_buf, e);
| ^^^ second mutable borrow occurs here
...
63 | }
| - first borrow ends here
I guessed that I can see the cause of the error, although I am not
sure how to fix it. So I tried a minimal reproduction. The best I can
come up with is this:
fn main() {
let mut v:Vec<usize> = vec![];
f1(&mut v);
}
fn f1(v:&mut Vec<usize>){
f2(v);
f3(v);
}
fn f2(v:&mut Vec<usize>){
println!("{}",v.len());
}
fn f3(v:&mut Vec<usize>){
println!("{}",v.len());
}
This seems to be of similar form to me: f1
gets a mutable reference to
a vector, then passes it mutable to f2
and f3
. But now rust seems
entirely happy.
My code is trying to use quick_xml to build a parser that recurses
down a tree. My thought was to hand the Vector buffers that it
requires around. Perhaps I need to create lots of new ones.