I'm trying to write a simple TCP echo server in Rust, and I'm a little confused over how to return a value from a match to Err.
I know the return type is supposed to be usize
, and I'd like to return a zero. In other languages, I would just return 0;
but Rust doesn't let me. I've also tried usize::Zero()
. I did get it to work by doing let s:usize = 0; s
but that seems awfully silly and I imagine there would be a better way to do it.
let buffer_length = match stream.read(&mut buffer) {
Err(e) => {
println!("Error reading from socket stream: {}", e);
// what do i return here?
// right now i just panic!
// return 0;
},
Ok(buffer_length) => {
stream.write(&buffer).unwrap();
buffer_length
},
};
I know I could also just not have the match
return anything and consume buffer_length
inside the match
with a function call or something, but I'd prefer not to in this case.
What is the most idiomatic way to handle something like this?
It is an enum with the variants, Ok(T) , representing success and containing a value, and Err(E) , representing error and containing an error value. Functions return Result whenever errors are expected and recoverable.
Rust has an extremely powerful control flow construct called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches.
The same way you "returned" buffer_length
from inside the Ok
arm, you can simply "return" a 0
from the Err
arm by leaving the trailing expression without return
or a semicolon.
return
always returns from a function. If you want to get the value of an expression, there's nothing you need to do in Rust. This always happens automatically.
This works for the same reason your let s = 0; s
workaround worked. All you did was insert a temporary variable, but you can also directly let the expression get forwarded to the outer expression.
let buffer_length = match stream.read(&mut buffer) {
Err(e) => {
println!("Error reading from socket stream: {}", e);
0
},
Ok(buffer_length) => {
stream.write(&buffer).unwrap();
buffer_length
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With