简体   繁体   English

在 Rust 中使用 unwrap_or_else 进行错误处理

[英]Using unwrap_or_else for error handling in Rust

I have a rust program that has a function 'is_input_sanitized' that takes an input String m, and checks if the input is free of special characters.The method is being used on a separate function in the following way.我有一个 rust 程序,它有一个函数“is_input_sanitized”,它接受一个输入字符串 m,并检查输入是否没有特殊字符。该方法以下列方式在单独的函数上使用。

let a = match is_input_sanitized(m) {
  Ok(m) => m,
  Err(_) => { return Err("error"); },
};

I am trying to convert this snippet into using 'unwrap_or_else' which will return an error when the input is not sanitized.I have read the documentation and have not been able to decipher a proper way to achieve this.我正在尝试将此代码段转换为使用“unwrap_or_else”,当输入未被清理时将返回错误。我已阅读文档并且无法破译实现此目的的正确方法。 Is this conversion possible?这种转换可能吗?

unwrap_or_else is for extracting Result values. unwrap_or_else用于提取Result值。 It sounds to me like you don't want to extract the result, so much as make a new one and propagate errors.在我看来,您不想提取结果,而是创建一个新结果并传播错误。 You have two different things you want to do here.你有两件不同的事情要做。 The first is that you want to change the error from whatever it started as (indicating by your _ in the pattern match) to something you control, and the second is that you want to return errors.第一个是您想要将错误从它开始的任何内容(由模式匹配中的_表示)更改为您控制的内容,第二个是您想要return错误。

Replacing the error can be done with map_err , which takes a function (such as a closure) and applies that function to the error if the Result is an Err .可以使用map_err替换错误,它接受一个函数(例如闭包),如果ResultErr ,则将该函数应用于错误。 If the result is Ok , then it returns the current Result unmodified.如果结果为Ok ,则返回未修改的当前Result

The second problem, returning on Err , is exactly what the question mark operator was invented for.返回Err的第二个问题正是问号运算符的发明目的。

Chaining results using match can get pretty untidy;使用 match 链接结果可能会变得非常混乱; luckily, the ?幸运的是, ? operator can be used to make things pretty again.运算符可用于使事情再次变得漂亮。 ? is used at the end of an expression returning a Result , and is equivalent to a match expression, where the Err(err) branch expands to an early return Err(From::from(err)) , and the Ok(ok) branch expands to an ok expression.用在返回Result的表达式的末尾,等效于匹配表达式,其中Err(err)分支扩展为提前return Err(From::from(err))Ok(ok)分支展开为ok表达式。

So what you're looking for is所以你要找的是

let a = is_input_sanitized(m).map_err(|_| "error")?;

Just is_input_sanitized(m).unwrap_or_else(|_| "error")?只是is_input_sanitized(m).unwrap_or_else(|_| "error")? . .

But if the error is simple, like "error" , it is better to use unwrap_or() : is_input_sanitized(m).unwrap_or("error")?但是如果错误很简单,比如"error" ,最好使用unwrap_or()is_input_sanitized(m).unwrap_or("error")? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM