Reputation: 103
I'm trying to print the address returned by peer_addr() of a TcpStream but Rust gives the error:
error: the trait
core::fmt::Display
is not implemented for the typecore::result::Result<std::net::addr::SocketAddr, std::io::error::Error>
[E0277] src/main.rs:29 format!("New client {}", stream.peer_addr());
According to the documentation Display is implemented.
Code is as follows:
use std::net::{TcpListener, TcpStream};
use std::thread;
fn main()
{
let listener = TcpListener::bind("127.0.0.1:80").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Accept err {}", e);
}
}
}
// close the socket server
drop(listener);
}
fn handle_client(stream: TcpStream) {
println!("New client {}", stream.peer_addr());
}
Upvotes: 0
Views: 990
Reputation: 88536
If you read the compiler error carefully you can see, that your variable is of the type core::result::Result<std::net::addr::SocketAddr, std::io::error::Error>
. You need to get the SocketAddr
out of there. Sadly, the documentation does not specify when an Err
value is returned. The easiest solution:
println!("New client {}", stream.peer_addr().unwrap());
Of course unwrap()
is evil and you should do proper error handling here!
Upvotes: 3