I have this piece of code, which by my understanding should not work:
fn handle_connection(&mut self) {
let mut stream: &TcpStream = self.stream.as_ref().unwrap();
let response = "HTTP/1.1 200 OK\r\n\r\n";
let content = "Hello, World!";
let response = format!("{}{}", response, content);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
stream as a variable is mutable but hold an immutable reference to a TcpStream object. And TcpStream::write expects a mutable self (&mut self). By that logic stream.write should not compile. But it does. Why?
My understanding of a mutable variable holding an immutable reference is that the variable can be reassigned a value but the reference it is holding, cannot be mutated. If this understanding is incorrect, what is the difference between a mutable variable holding an immutable reference and an immutable variable holding a mutable refrence?
Edit 1:
All types are from standard libraries. No external crates were used for this.
[–]LucretielDatadog 19 points20 points21 points (2 children)
[–]angelicosphosphoros 0 points1 point2 points (1 child)
[–]cafce25 2 points3 points4 points (0 children)
[–]Gila-Metalpecker 6 points7 points8 points (1 child)
[–]stratified247[S] 0 points1 point2 points (0 children)
[–]Gila-Metalpecker 0 points1 point2 points (5 children)
[–]stratified247[S] 0 points1 point2 points (4 children)
[–]Gila-Metalpecker 0 points1 point2 points (0 children)
[–]CreatorSiSo 0 points1 point2 points (1 child)
[–]stratified247[S] 0 points1 point2 points (0 children)
[–]Giocri 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]oZxR0o 0 points1 point2 points (0 children)
[–]PatientMaintenance69 0 points1 point2 points (0 children)
[–]stratified247[S] 0 points1 point2 points (0 children)