Skip to content

Commit 48bed57

Browse files
committed
Use try! for the illustration of calling it in main
Until rust-lang/rust#35946 is fixed, so that the error message is clearer than not implementing the Carrier trait.
1 parent e98eab8 commit 48bed57

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

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

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -218,34 +218,30 @@ fn read_username_from_file() -> Result<String, io::Error> {
218218
Much nicer, right? The `try!` macro and the `?` operator make propagating
219219
errors upwards much more ergonomic. There's one catch though: they can only be
220220
used in functions that return a `Result`, since they expand to the same `match`
221-
expression we saw above that had a potential early return of an `Err` value. Let's look at what happens if we try to use `?` in the `main` function, which has a return type of `()`:
221+
expression we saw above that had a potential early return of an `Err` value.
222+
Let's look at what happens if we try to use `try!` in the `main` function,
223+
which you'll recall has a return type of `()`:
222224

223225
```rust,ignore
224-
#![feature(question_mark)]
225226
# use std::fs::File;
226227
fn main() {
227-
let f = File::open("hello.txt")?;
228+
let f = try!(File::open("hello.txt"));
228229
}
229230
```
230231

232+
<!-- NOTE: as of 2016-10-12, the error message when calling `?` in a function
233+
that doesn't return a result is confusing. `try!` isn't as bad, so I'm using
234+
that. When https://github.com/rust-lang/rust/issues/35946 is fixed, we can
235+
switch this example to use `?`. /Carol -->
236+
231237
When we compile this, we get the following error message:
232238

233239
```bash
234-
```
235-
236-
237-
238-
239-
There's one problem though; let's try compiling the example:
240-
241-
```rust,ignore
242-
Compiling result v0.1.0 (file:///projects/result)
243240
error[E0308]: mismatched types
244-
--> src/main.rs:6:13
241+
-->
245242
|
246-
6 | let f = File::open("hello.txt")?;
247-
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum
248-
`std::result::Result`
243+
3 | let f = try!(File::open("hello.txt"));
244+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
249245
|
250246
= note: expected type `()`
251247
= note: found type `std::result::Result<_, _>`

0 commit comments

Comments
 (0)