从匹配返回值到 Err(e) [英] Return value from match to Err(e)

查看:39
本文介绍了从匹配返回值到 Err(e)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Rust 编写一个简单的 TCP 回显服务器,但我对如何将匹配项中的值返回给 Err 有点困惑.

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.

我知道返回类型应该是 usize,我想返回一个零.在其他语言中,我只会 return 0; 但 Rust 不允许我这样做.我也试过 usize::Zero().我确实通过执行 let s:usize = 0; 让它工作了.s 但这似乎非常愚蠢,我想会有更好的方法来做到这一点.

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

我知道我也可以不让 match 返回任何内容并使用函数调用或其他方式在 match 中消耗 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?

推荐答案

与您从 Ok 分支内部返回"buffer_length 相同的方式,您可以简单地返回"" 来自 Err 分支的 0 留下不带 return 或分号的尾随表达式.

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 总是从函数返回.如果你想获得一个表达式的值,在 Rust 中你不需要做任何事情.这总是自动发生.

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.

这与您的 let s = 0; 的原因相同;s 解决方法有效.您所做的只是插入一个临时变量,但您也可以直接让表达式转发到外部表达式.

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

这篇关于从匹配返回值到 Err(e)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆