I'm new to Rust and have my difficulties with the borrow checker.
Calling consume_byte
from main
works just fine. But if I try to add another function (consume_two_bytes
) in between it all falls apart.
The following code won't compile since it seems like the reader
variable in consume_two_bytes
is not mutable and cant be borrowed.
Adding a &mut
in the function signature just changes the compiler error.
use std::io::Read;
use std::net::TcpListener;
fn consume_byte<R>(reader: R) where R: Read {
let mut buffer = vec![];
reader.take(1).read_to_end(&mut buffer).unwrap();
}
fn consume_two_bytes<R>(reader: R) where R: Read {
consume_byte(&mut reader);
consume_byte(&mut reader);
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let (mut stream, _) = listener.accept().unwrap();
consume_byte(&mut stream);
consume_byte(&mut stream);
consume_two_bytes(&mut stream);
}
reader
has to be mutable in consume_two_bytes
:
fn consume_two_bytes<R>(mut reader: R) where R: Read { // note the mut
consume_byte(&mut reader);
consume_byte(&mut reader);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With