我们什么时候应该在 Rust 中使用 unwrap 和 expect [英] When should we use unwrap vs expect in Rust
问题描述
我是 Rust 的新手,并试图了解我们什么时候应该使用 unwrap 和 expect.
I'm new to rust and trying to understand when should we use unwrap vs expect.
这是一个示例代码:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let query = args.get(1).unwrap();
println!("query from unwrawp: {}", query);
let query = args.get(1).expect("insufficient arguments");
println!("query from expect: {}", query);
//$ cargo run hello
//OUTPUT:
//query from expect: hello
//query from unwrawp: hello
}
我观察到的唯一区别是期望中有一个自定义的恐慌消息.
这两个是可以互换的,还是有什么特殊的场景我们应该使用一个而不是另一个?
Only difference I observed is there's a custom panic message in expect.
Are these two interchangeable or are there any special scenarios where we should use one over the other?
推荐答案
Rust 没有函数重载,所以应该有一种方法来声明unwrap
with a message",那就是expect
.
Rust doesn't have function overloading, so there should be a way to declare "unwrap
with a message", and that is expect
.
expect
==unwrap
带有消息expect_err
==unwrap_err
带有消息
expect
==unwrap
with a messageexpect_err
==unwrap_err
with a message
关于unwrap vs expect"的使用场景Rust Book(第 9 章) 说:
About usage scenarios of "unwrap vs expect" Rust Book (Ch 9) says:
使用 expect 而不是 unwrap 并提供良好的错误消息可以传达您的意图并更容易追踪恐慌的来源.因为此错误消息以我们指定的文本开头...更容易找到此错误消息来自代码的何处.
Using expect instead of unwrap and providing good error messages can convey your intent and make tracking down the source of a panic easier. Because this error message starts with the text we specified... it will be easier to find where in the code this error message is coming from.
这篇关于我们什么时候应该在 Rust 中使用 unwrap 和 expect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!