I am building a bitcoin clone that needs to be able to connect to other sockets and send information between them. How do I try to connect to another socket and if the socket doesn't respond just continue with the code instead of crashing the whole program?
This is kind of what I think the code would look like:
use std::io::prelude::*;
use std::net::TcpStream;
fn main()
{
for node in nodes {
let mut stream = TcpStream::connect(node).unwrap();
if successful_connection {
break;
}
}
}
CodePudding user response:
The problem is that you use unwrap()
. From its docs:
Panics if the value is an
Err
, with a panic message provided by theErr
’s value.
This function's purpose is to abort your program if the operation has failed, and so:
Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the
Err
case explicitly, or callunwrap_or
,unwrap_or_else
, orunwrap_or_default
.
In case you want to do something only if the operation has succeeded, and do nothing in the other case, if let
is your best friend:
if let Ok(stream) = TcpStream::connect(node) {
// Do something with `stream`
}
If you also want to handle the error case, you can use match
:
match TcpStream::connect(node) {
Ok(stream) => {
// Do something with `stream`
}
Err(error) => {
// Handle the error
}
}