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
The question mark operator (`?`) unwraps valid values or returns erroneous values, propagating them to the calling function.
202
-
203
-
r[expr.try.restricted-types]
204
-
It is a unary postfix operator that can only be applied to the types `Result<T, E>` and `Option<T>`.
205
-
206
-
r[expr.try.behavior-std-result]
207
-
When applied to values of the `Result<T, E>` type, it propagates errors.
208
-
209
-
r[expr.try.effects-err]
210
-
If the value is `Err(e)`, then it will return `Err(From::from(e))` from the enclosing function or closure.
211
-
212
-
r[expr.try.result-ok]
213
-
If applied to `Ok(x)`, then it will unwrap the value to evaluate to `x`.
214
-
215
-
```rust
216
-
# usestd::num::ParseIntError;
217
-
fntry_to_parse() ->Result<i32, ParseIntError> {
218
-
letx:i32="123".parse()?; // x = 123
219
-
lety:i32="24a".parse()?; // returns an Err() immediately
220
-
Ok(x+y) // Doesn't run.
221
-
}
222
-
223
-
letres=try_to_parse();
224
-
println!("{:?}", res);
225
-
# assert!(res.is_err())
226
-
```
227
-
228
-
r[expr.try.behavior-std-option]
229
-
When applied to values of the `Option<T>` type, it propagates `None`s.
230
-
231
-
r[expr.try.effects-none]
232
-
If the value is `None`, then it will return `None`.
233
-
234
-
r[expr.try.result-some]
235
-
If applied to `Some(x)`, then it will unwrap the value to evaluate to `x`.
201
+
The try propagation expression uses the value of the inner expression and the [`Try`] trait to decide whether to produce a value, and if so, what value to produce, or whether to return a value to the caller, and if so, what value to return.
202
+
203
+
> [!EXAMPLE]
204
+
> ```rust
205
+
> # usestd::num::ParseIntError;
206
+
> fntry_to_parse() ->Result<i32, ParseIntError> {
207
+
> letx:i32="123".parse()?; // `x` is `123`.
208
+
> lety:i32="24a".parse()?; // Returns an `Err()` immediately.
0 commit comments