Rust 中的 unwrap 是什么,它有什么用途?

问题描述:

我有这个使用 .unwrap() 的代码:

I have this code that uses .unwrap():

fn main() {
    let paths = std::fs::read_dir("/home/user").unwrap();

    for path in paths {
        println!("Name: {}", path.unwrap().path().display());

    }
}

查看定义后解包,

pub fn unwrap(self) -> T {
  match self {
        Ok(t) => t,
        Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
    }
}

以及 签名>read_dir

pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir>

我是否正确理解 unwrap 返回在 Result 中传递的 T 类型?

Am I correct in understanding that unwrap returns the T type that is passed in Result?

在 Rust 中,当您的操作可能返回 T 或失败时,您将拥有 ResultOption(E 将是发生有趣错误时的错误条件).

In Rust, when you have an operation that may either return a T or fail, you will have a value of type Result<T,E> or Option<T> (E will be the error condition in case of an interesting error).

函数 unwrap(self) ->T 会给你嵌入的 T 如果有的话.如果不是 T 而是 ENone 那么它会恐慌.

The function unwrap(self) -> T will give you the embedded T if there is one. If instead there is not a T but an E or None then it will panic.

最好在您确定没有错误时使用.如果情况并非如此,通常最好对错误进行模式匹配或使用 try! ? 运算符来转发错误.

It is best used when you are positively sure that you don't have an error. If that is not the case usually it is better either pattern-match the error or use the try! macro ? operator to forward the error.

在您的示例中,对 read_dir() 的调用将返回 io::Result,因为打开目录可能会失败.并且迭代打开的目录会返回多个 io::Result 类型的值,因为读取目录也可能会失败.

In your example, the call to read_dir() returns a io::Result<ReadDir> because opening the directory might fail. And iterating the opened directory returns multiple values of type io::Result<DirEntry> because reading the directory might also fail.

使用 try! ? 会是这样的:

fn try_main() -> std::io::Result<()> {
    let entries = std::fs::read_dir("/home/user")?;

    for entry in entries {
        println!("Name: {}", entry?.path().display());

    }
    Ok(())
}

fn main() {
    let res = try_main();

    if let Err(e) = res {
        println!("Error: {}", e);
    }
}

看看如何检查每个错误案例.

Look how every error case is checked.

(更新为使用 ? 而不是 try!().宏仍然有效,但 ? 是新代码的首选).

(Updated to use ? instead of try!(). The macro still works, but the ? is preferred for new code).