As I was trying to understand the differences between a mutable variable, which happens to be a reference, e.g. let mut x: &i32 vs mutable references, e.g. let x: &mut i32, I found this difference I can't understand:
This works, where by_ref has the signature: fn by_ref(&mut self) -> &mut Self (docs)
fn example(mut t: &TcpStream) {
t.by_ref();
}
But the following with String, using a method with a similar looking signature, reserve:
pub fn reserve(&mut self, additional: usize)`
But this does not work, the error is:
"cannot borrow
*stras mutable, as it is behind a&reference"
fn example(mut str: &String) {
str.reserve(10);
}
Interesting to note that these two examples with mutable references work, and are, as far I know, the recommended way to use mutable methods:
fn example_stream(t: &mut TcpStream) {
t.by_ref();
}
fn example_string(str: &mut String) {
str.reserve(10);
}
So what is different between a TcpStream and a String that allows methods with a &mut self argument to be called in one case and not in the other?