File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,39 @@ unpleasant error message.
45
45
To improve the quality of our error message, we should be more specific
46
46
about the return type and consider explicitly handling the error.
47
47
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
+
48
79
[ option ] : https://doc.rust-lang.org/std/option/enum.Option.html
49
80
[ result ] : https://doc.rust-lang.org/std/result/enum.Result.html
50
81
[ 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
You can’t perform that action at this time.
0 commit comments