[英]Rust shorthand for Result<type, Box<dyn std::error::Error>>
When doing error catching I usually make a function return a result.在进行错误捕获时,我通常使函数返回结果。 But I feel like writing Result<type, Box<...>> everytime is really verbose, is there some built-in shorthand for this?
但是我觉得每次都写 Result<type, Box<...>> 真的很冗长,是否有一些内置的速记?
fn something() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
You can just define a type alias with generic arguments.您可以使用泛型参数定义类型别名。 Many crates do like this:
许多板条箱是这样的:
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn something() -> Result<()> {
Ok(())
}
The anyhow
crate, written by the author of serde, is designed around an ergonomic alternative to Box<dyn std::error::Error>
called anyhow::Error
.在
anyhow
板条箱,通过SERDE的作者写的,是围绕到符合人体工程学的替代Box<dyn std::error::Error>
称为anyhow::Error
。 It defines anyhow::Result<T>
as alias for Result<T, anyhow::Error>
:它定义了
anyhow::Result<T>
作为Result<T, anyhow::Error>
别名:
fn something() -> anyhow::Result<()> {
Ok(())
}
The downside is that it's an external crate, although a very popular and well-tested one.缺点是它是一个外部板条箱,尽管它非常受欢迎且经过充分测试。
The upside is that you get good ergonomics, additional features (such as context()
and with_context()
on Result
), as well as non-trivial optimizations - anyhow::Error
is a narrow pointer rather than a wide one, so your Result
s are smaller and more efficient compared to Box<dyn Error>
.好处是您可以获得良好的人体工程学、附加功能(例如
Result
上的context()
和with_context()
),以及非平凡的优化 - anyhow::Error
是一个窄指针而不是一个宽指针,因此您的Result
与Box<dyn Error>
相比,s 更小更高效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.