Hi all, I'm trying to learn about rust's trait, and I wrote this code:
use std::io;
trait SomeReadExt: io::BufRead {
fn read_number(&mut self) -> io::Result<i64> {
let mut buff: [u8; 2] = [0; 2];
self.read_exact(&mut buff)?;
Ok(((buff[0] as i64) << 8) | (buff[1] as i64))
}
}
impl<R: io::BufRead> SomeReadExt for R {}
pub trait SomeRead: io::BufRead {
fn read_value(&mut self) -> io::Result<Vec<u8>> {
let n = self.read_number()?;
let mut buff = vec![0u8; n as usize];
self.read_exact(&mut buff)?;
Ok(buff)
}
}
impl<R: io::BufRead> SomeRead for R {}
But somehow, it got this error
error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
--> src/test.rs:15:17
|
15 | let n = self.read_number()?;
| ^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
You can also reproduce it in this playground: Rust Playground.
I don't understand why self
can't be borrow as mutable while self
itself is a &mut Self
. Is there any explanation for this error? Thank you.