这些解压有必要吗?

Jus*_*ner 0 multithreading rust

我是 Rust 新手,我看到很多代码如下所示:

use std::thread;

fn main() {
    println!("So we start the program here!");
    let t1 = thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(200));
        println!("We create tasks which gets run when they're finished!");
    });

    let t2 = thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(100));
        println!("We can even chain callbacks...");
        let t3 = thread::spawn(move || {
            thread::sleep(std::time::Duration::from_millis(50));
            println!("...like this!");
        });
        t3.join().unwrap();
    });
    println!("While our tasks are executing we can do other stuff here.");

    t1.join().unwrap();
    t2.join().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,他们调用join()后跟unwrap(),但他们不使用未包装的东西。我尝试删除这些unwrap(),它仍然有效。这些有unwrap()必要吗?我还注意到甚至 Rust 书也使用这种语法。

Mar*_*ini 5

unwrap()是访问结果或选项值的简写。当您编写一些示例代码时没有问题,因为您不想处理错误处理。如果你删除unwrap()这里一切都会正常。

如果由于某种原因返回错误,情况会有所不同。在这种情况下,无论有或没有,您的程序都会有不同的行为unwrap()

如果您有unwrap(),错误条件将退出程序。如果您不使用unwrap(),程序将继续忽略错误。

如前所述,这对于一小段代码来说很好,但在现实场景中,不unwrap()应该存在,而是您应该处理错误情况。

  • 我想补充一点,在现实世界的代码中,如果您“想要”在出现错误时硬崩溃程序,您应该使用“expect()”,而不是“unwrap()”。它的工作原理相同,但可以让您提供更好的错误消息“Option was none”。 (3认同)