? 在 main 和 tests 中

Rust的错误处理围绕返回 Result <T,E> 并使用 ? 传播错误。
对于那些编写许多小程序并且希望进行许多测试的人来说,更关注于那些复杂的入口,例如main和#[test]中的错误处理。
举个例子,你将尝试这样写:
1. use std::fs::File;
3. fn main() {
4. let f = File::open("bar.txt")?;
5. }
因为 ? 通过处理 Result 并提前返回函数来工作,所以上面的代码不起作用,并且导致以下错误:
1. error[E0277]: the `?` operator can only be used in a function that returns `Result`
2. or `Option` (or another type that implements `std::ops::Try`)
3. --> src/main.rs:5:13
4. |
5. 5 | let f = File::open("bar.txt")?;
6. | ^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
7. |
8. = help: the trait `std::ops::Try` is not implemented for `()`
9. = note: required by `std::ops::Try::from_error`
在 Rust 2015 中,处理这种问题,需要这样:
1. // Rust 2015
3. # use std::process;
4. # use std::error::Error;
6. fn run() -> Result<(), Box<Error>> {
7. // real logic..
8. Ok(())
9. }
11. fn main() {
12. if let Err(e) = run() {
13. println!("Application error: {}", e);
14. process::exit(1);
15. }
16. }
但是,在这种情况下,run 函数具有所有有趣的逻辑,而 main 只是样板。 问题更糟糕的是 #[test],因为它们往往会有更多这种情况。
在 Rust 2018 中,你可以使得你的 #[test] 和 main 函数返回一个 Result:
1. // Rust 2018
3. use std::fs::File;
5. fn main() -> Result<(), std::io::Error> {
6. let f = File::open("bar.txt")?;
8. Ok(())
9. }
在这种情况下,如果说文件不存在并且某处有一个 Err(err),那么 main 将以错误代码(不是0)退出并打印出 Debug 表示 err。
更多的细节
使 - > Result <..> 在 main 和 #[test] 的上下文中工作并不神奇。
它全部由 Termination 特征支持,所有有效的返回类型的 main 和测试函数必须实现。 特征定义为:
1. pub trait Termination {
2. fn report(self) -> i32;
3. }
在为应用程序设置入口点时,编译器将使用此特征并在您编写的 main 函数的 Result 上调用 .report()。
Result 和 () 的这个特性的两个简化示例实现是:
1. # #![feature(process_exitcode_placeholder, termination_trait_lib)]
2. # use std::process::ExitCode;
3. # use std::fmt;
4. #
5. # pub trait Termination { fn report(self) -> i32; }
7. impl Termination for () {
8. fn report(self) -> i32 {
9. # use std::process::Termination;
10. ExitCode::SUCCESS.report()
11. }
12. }
14. impl<E: fmt::Debug> Termination for Result<(), E> {
15. fn report(self) -> i32 {
16. match self {
17. Ok(()) => ().report(),
18. Err(err) => {
19. eprintln!("Error: {:?}", err);
20. # use std::process::Termination;
21. ExitCode::FAILURE.report()
22. }
23. }
24. }
25. }
正如您在 () 中看到的那样,只返回成功代码。
在 Result 的情况下,成功的话交给 () 来执行,错误的话,交给 Err(..),打印出错误消息并退出代码。
