44

In Rust, I believe the idiomatic way to deal with recoverable errors is to use Result. For example this function clearly is idiomatic:

fn do_work() -> Result<u64, WorkError> {...}

Of course, there are also functions that have a single, obvious, failure state, and therefore use the Option type instead. An idiomatic example would be this:

fn do_work() -> Option<u64>

This all is straightforwardly addressed in the documentation. However, I'm confused about the case where a function can fail, but has no meaningful value when successful. Compare the following two functions:

fn do_work() -> Option<WorkError>
// vs
fn do_work() -> Result<(), WorkError>

I'm just not sure which one of these is more idiomatic, or is used more often in real world Rust code. My go-to resource for questions like this is the Rust book, but I don't think this is addressed in its "Error Handling" section. I haven't had much luck with any other Rust documentation either.

Of course this seems pretty subjective, but I'm looking for authoritative sources that either state which form is idiomatic, or on why one form is superior (or inferior) to the other. (I'm also curious how the convention compares to other languages that heavily utilize "errors as values", like Go and Haskell.)

4

2 回答 2

46

使用fn do_work() -> Result<(), WorkError>.

Result<(), WorkError>意味着您希望完成工作,但它可能会失败。

Option<WorkError>意味着你想得到一个错误,但它可能不存在。

您可能希望完成工作,但不要在编写时出错do_work(),因此Result<(), WorkError>是更好的选择。

我希望Option<WorkError>只在像fn get_last_work_error() -> Option<WorkError>.

于 2016-04-27T00:59:26.833 回答
6

Rust 是“非常强类型的”(请不要告诉我我如何衡量一种语言的强类型......)。我的意思是,Rust 通常为您提供让类型为您“说话”并记录您的代码的工具,因此使用此功能编写可读代码是惯用的。

换句话说,您要问的问题应该是“哪种类型最能代表函数对读取其签名的任何人的作用?”

因为Result<(), Workerror>您可以直接从文档中看到

Result 是表示成功 (Ok) 或失败 (Err) 的类型

因此,专门针对您的情况,这意味着如果您的函数成功(由 表示Ok<()>)或WorkError出现错误(Err<WorkError>),则不会返回任何内容。这是您在问题中描述函数的方式的代码中非常直接的表示。

将此与Option<WorkError>或进行比较Option<()>

Type Option 表示一个可选值:每个 Option 要么是 Some 并且包含一个值,要么是 None,并且不

在您的情况下,您Option<WorkError>会对读者说“这个函数应该返回 aWorkError但它可能什么也不返回”。您可以记录“不返回任何内容”的情况意味着该函数实际上是成功的,但这仅从类型中并不是很明显。

Option<()>说“这个函数不能返回任何东西或没有有意义的返回”,如果WorkError不包含其他信息(如错误类型或错误消息),这可能是一个合理的说法,它实际上只是说“发生错误”的一种方式”。在这种情况下,一个简单bool的包含相同的信息......否则,Result您可以返回一些与错误相关的更多信息。

于 2016-04-27T12:37:19.883 回答