Question about mut &

Code

Why in test2 there are compilation error and in test1 not? both read_to_end and S::f has &mut self. Both functions (test1,test2) have mut variable and immutable reference. I'm confused.

It's possible to call read_to_end on a &TcpStream because &TcpStream implements the Read trait that provides read_to_end. Basically, reading from a TcpStream doesn't require mutable access. On the other hand, calling the f function on S requires having a mutable reference because it's declared with a &mut self argument.

mut s: &S doesn't do what you think it does. If you want to accept a mutable reference, you should write s: &mut S. That would mean that s will have &mut S value. mut s: &S means that s has &S value (an immutable, shared reference), and mut in that position allows you to reassign another reference to the s local variable. That's usually not desirable.

calling the f function on S requires having a mutable reference because it's declared with a &mut self argument

But read_to_end has &mut self too in signature. It must take s by mutable reference but s is behind immutable reference.

That would be correct for trait implementation on TcpStream (which also exists). But in your code the implementation of Read for &TcpStream takes effect. In that implementation, Self is &TcpStream, so &mut self in the function signature expands to &mut &TcpStream. Having a &TcpStream, you can make a &mut &TcpStream from it. Note that you won't be able to get a &mut TcpStream out of &mut &TcpStream.

1 Like

Now i understand. Thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.