Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to re-borrow a variable because I cannot borrow immutable local variable as mutable

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);
}
like image 265
Donald H Avatar asked Jul 25 '15 20:07

Donald H


1 Answers

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);
}
like image 79
fjh Avatar answered Nov 15 '22 08:11

fjh