cannot borrow foo as immutable because it is also borrowed as mutable

Viewed 2244

I have following (innocent enough) Rust code:

let file = &Path(some_file_name);
let mut buf = [0u8, ..12];
match io::file_reader(file) {
    Ok(reader) => reader.read(buf, buf.len()),
    Err(msg) => println(msg)
}

The rustc complains that

cannot borrow buf[] as immutable because it is also borrowed as mutable

If changing the corresponding line to:

Ok(reader) => reader.read(buf, 12),

all will work just fine. But it is less satisfactory since now the length of the buffer is duplicated in the code. Although vaguely understanding why rustc complains, I still would like to argue that rustc should be able to infer that len() is a pure function and has no side effect so the code is valid. Besides, it is a quite common patten to read into a buffer that way.

So what is the idiomatic Rust way here?

EDIT: The code was for Rust 0.8. As @pnkfelix pointed out, the Reader.read API has been changed since then. It doesn't need the second parameter any more.

1 Answers
Related