@@ -489,25 +489,37 @@ fn main() {
489
489
When we compile this code, we get the following error message:
490
490
491
491
``` 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`)
493
493
--> src/main.rs:4:13
494
494
|
495
495
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 `()`
501
497
|
502
498
= help: the trait `std::ops::Try` is not implemented for `()`
503
499
= note: required by `std::ops::Try::from_error`
504
500
```
505
501
506
502
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."
511
523
512
524
Now that we’ve discussed the details of calling ` panic! ` or returning ` Result ` ,
513
525
let’s return to the topic of how to decide which is appropriate to use in which
0 commit comments