Return value from correspondence in Err (e)

I'm trying to write a simple TCP echo server in Rust, and I'm a little confused about how to return a value from a match in Err.

I know what return type should be usize, and I would like to return zero. In other languages, I would be simple return 0;, but Rust does not allow me. I also tried usize::Zero(). I did it for work by doing let s:usize = 0; s, but it seems awfully stupid, and I believe that there will be a better way to do this.

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 that I could just not return matchanything and consume buffer_lengthinternally matchwith a function call or something like that, but I would prefer not in this case.

What is the most idiomatic way to deal with something like this?

+4
source share
1

, "" buffer_length Ok, "" 0 Err, return .

return . , Rust. .

, let s = 0; s. , , , .

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
    },
};
+8

Source: https://habr.com/ru/post/1611534/


All Articles