11

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jmoggr
  • 277
  • 2
  • 4
  • 8
  • 2
    It's not clear what your problem actually is. "Return value from match to Err(e)" just doesn't make any sense, and everything you've described sounds like it *should* work. Your best bet is to update the question including a minimal, compilable example of what you're trying and the output of the compiler. Also, a clear indication of what *result* you're trying to get (what should happen after this "return") would help. – DK. Oct 14 '15 at 04:28

1 Answers1

16

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
    },
};
oli_obk
  • 28,729
  • 6
  • 82
  • 98