2 个稳定版本
使用旧的 Rust 2015
| 1.0.1 | 2023 年 7 月 28 日 | 
|---|---|
| 1.0.0 | 2021 年 12 月 14 日 | 
#879 在 Rust 模式
每月 40 次下载
用于  2 crates
4KB
unwrap_or
Unwrap-or 提供了四个宏,允许您在调用函数的相同作用域中使用代码。它们类似于 Rust 的 unwrap_or_else,但提供的代码不在闭包中,而是在函数本身中。
这允许您编写更灵活的内容。当发生错误时,您可以拥有 return、break 或 continue 语句,而无需担心任何复杂的返回逻辑。您还可以直接引用调用函数中的变量,而无需将它们移动到闭包中。
以下是一个使用示例
fn a_function_which_may_fail() -> Result<String, String> {
	Error("There was an error!")
}
fn another_function() -> Result<(), String> {
	let _ok_value = unwrap_ok_or!(a_function_which_may_fail(), error_value, {
		log(error_value);
		return error_value;
	});
	Ok(())
}
上面的宏展开为一个简单的 match 函数
let _ok_value = match a_function_which_may_fail() {
	Ok(v) => v,
	Err(error_value) => {
		log(error_value);
		return error_value;
	}
}
有四个具有这种语法的函数
let ok_value = unwrap_ok_or!(function_returning_result, error_variable_name, code_to_run_on_error);
let error_value = unwrap_err_or!(function_returning_result, ok_variable_name, code_to_run_on_ok);
let some_value = unwrap_some_or!(function_returning_option, code_to_run_on_none);
let none_value = unwrap_none_or!(function_returning_option, some_variable_name, code_to_run_on_some);