0

I'm playing with a function that handles a TCP connection:

use std::{io::Write, net::TcpStream, sync::Arc};

fn handle_connection(stream: TcpStream) {
    let data = "Hello!\n";

    let stream_arc = Arc::new(stream);
    let mut s: &TcpStream = &*stream_arc; //let mut s = Deref::deref(&stream_arc);

    s.write_all(data.as_bytes()).unwrap(); //same as Write::write_all(&mut s, data.as_bytes()).unwrap();
}

I can't figure out why Rust doesn't complain about Write::write_all since s is not a mutable reference. I noticed also that removing mut from s compilation fails. Am I missing some trait implementation that permits this? Is this a way to mutably borrow from std::sync::Arc?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
MirkoBanchi
  • 2,173
  • 5
  • 35
  • 52
  • 1
    TL;DR the duplicates: Calling a method will automatically take a (mutable) borrow of a variable. `Write` is implemented for [immutable references to `TcpStream`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#impl-Write-1). You have a `&mut &TcpStream`. – Shepmaster Apr 07 '20 at 13:26
  • @Shepmaster Oh, thanks, i missed that implementation. – MirkoBanchi Apr 07 '20 at 14:44
  • 1
    You'll note that one of the duplicates is my own question, so I was once in the same position as you! – Shepmaster Apr 07 '20 at 14:58

0 Answers0