Skip to content

Commit 4a49809

Browse files
committed
talk about main being able to return Result
Fixes #1289
1 parent 73e5e73 commit 4a49809

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

2018-edition/src/ch09-02-recoverable-errors-with-result.md

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -489,25 +489,37 @@ fn main() {
489489
When we compile this code, we get the following error message:
490490

491491
```text
492-
error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
492+
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
493493
--> src/main.rs:4:13
494494
|
495495
4 | let f = File::open("hello.txt")?;
496-
| ------------------------
497-
| |
498-
| the `?` operator can only be used in a function that returns
499-
`Result` (or another type that implements `std::ops::Try`)
500-
| in this macro invocation
496+
| ^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
501497
|
502498
= help: the trait `std::ops::Try` is not implemented for `()`
503499
= note: required by `std::ops::Try::from_error`
504500
```
505501

506502
This error points out that we’re only allowed to use `?` in a function that
507-
returns `Result`. In functions that don’t return `Result`, when you call other
508-
functions that return `Result`, you’ll need to use a `match` or one of the
509-
`Result` methods to handle the `Result` instead of using `?` to potentially
510-
propagate the error to the calling code.
503+
returns `Result<T, E>`. In functions that don’t return `Result<T, E>`, when
504+
you call other functions that return `Result<T, E>`, you’ll need to use a
505+
`match` or one of the `Result<T, E>` methods to handle the `Result<T, E>`
506+
instead of using `?` to potentially propagate the error to the calling code.
507+
508+
However, the `main` function can return a `Result<T, E>`:
509+
510+
```rust,ignore
511+
use std::error::Error;
512+
use std::fs::File;
513+
514+
fn main() -> Result<(), Box<dyn Error>> {
515+
let f = File::open("hello.txt")?;
516+
517+
Ok(())
518+
}
519+
```
520+
521+
The `Box<dyn Error>` is called a "trait object", which we'll talk about in Chapter 17.
522+
For now, you can read `Box<dyn Error>` to mean "any kind of error."
511523

512524
Now that we’ve discussed the details of calling `panic!` or returning `Result`,
513525
let’s return to the topic of how to decide which is appropriate to use in which

0 commit comments

Comments
 (0)