Skip to content

Commit 506b375

Browse files
authored
Merge pull request #1108 from maccoda/master
Return Result from main function.
2 parents bc342a4 + 636b289 commit 506b375

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/error/result.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,39 @@ unpleasant error message.
4545
To improve the quality of our error message, we should be more specific
4646
about the return type and consider explicitly handling the error.
4747

48+
## Using `Result` in `main`
49+
50+
The `Result` type can also be the return type of the `main` function if
51+
specified explicitly. Typically the `main` function will be of the form:
52+
53+
```rust
54+
fn main() {
55+
println!("Hello World!");
56+
}
57+
```
58+
59+
However `main` is also able to have a return type of `Result`. If an error
60+
occurs within the `main` function it will return an error code and print a debug
61+
representation of the error (using the [`Debug`] trait). The following example
62+
shows such a scenario and touches on aspects covered in [the following section].
63+
64+
```rust,editable
65+
use std::num::ParseIntError;
66+
67+
fn main() -> Result<(), ParseIntError> {
68+
let number_str = "10";
69+
let number = match number_str.parse::<i32>() {
70+
Ok(number) => number,
71+
Err(e) => return Err(e),
72+
};
73+
println!("{}", number);
74+
Ok(())
75+
}
76+
```
77+
78+
4879
[option]: https://doc.rust-lang.org/std/option/enum.Option.html
4980
[result]: https://doc.rust-lang.org/std/result/enum.Result.html
5081
[parse]: https://doc.rust-lang.org/std/primitive.str.html#method.parse
82+
[`Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
83+
[the following section]: error/result/early_returns.html

0 commit comments

Comments
 (0)