You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Much nicer, right? The `try!` macro and the `?` operator make propagating
219
219
errors upwards much more ergonomic. There's one catch though: they can only be
220
220
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 `()`:
222
224
223
225
```rust,ignore
224
-
#![feature(question_mark)]
225
226
# use std::fs::File;
226
227
fn main() {
227
-
let f = File::open("hello.txt")?;
228
+
let f = try!(File::open("hello.txt"));
228
229
}
229
230
```
230
231
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
+
231
237
When we compile this, we get the following error message:
232
238
233
239
```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)
243
240
error[E0308]: mismatched types
244
-
--> src/main.rs:6:13
241
+
-->
245
242
|
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`
0 commit comments