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 书也使用这种语法。
这unwrap()是访问结果或选项值的简写。当您编写一些示例代码时没有问题,因为您不想处理错误处理。如果你删除unwrap()这里一切都会正常。
如果由于某种原因返回错误,情况会有所不同。在这种情况下,无论有或没有,您的程序都会有不同的行为unwrap()。
如果您有unwrap(),错误条件将退出程序。如果您不使用unwrap(),程序将继续忽略错误。
如前所述,这对于一小段代码来说很好,但在现实场景中,不unwrap()应该存在,而是您应该处理错误情况。
| 归档时间: |
|
| 查看次数: |
578 次 |
| 最近记录: |