Skip to content

Commit 8b668fc

Browse files
authored
Merge pull request #176 from Havvy/try_option
Document that ? works for Option
2 parents 508674a + 8a759b6 commit 8b668fc

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

src/expressions/operator-expr.md

+29-6
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,16 @@ let y = &mut 9;
8484
assert_eq!(*y, 11);
8585
```
8686

87-
## The `?` operator
87+
## The question mark operator
8888

89-
The `?` ("question mark") operator can be applied to values of the `Result<T,
90-
E>` type to propagate errors. If applied to `Err(e)` it will return
91-
`Err(From::from(e))` from the enclosing function or closure. If applied to
92-
`Ok(x)` it will unwrap the value to return `x`. Unlike other unary operators
93-
`?` is written in postfix notation. `?` cannot be overloaded.
89+
The question mark operator (`?`) unwraps valid values or returns errornous
90+
values, propagating them to the calling function. It is a unary postfix
91+
operator that can only be applied to the types `Result<T, E>` and `Option<T>`.
92+
93+
When applied to values of the `Result<T, E>` type, it propagates errors. If
94+
the value is `Err(e)`, then it will return `Err(From::from(e))` from the
95+
enclosing function or closure. If applied to `Ok(x)`, then it will unwrap the
96+
value to evaulate to `x`.
9497

9598
```rust
9699
# use std::num::ParseIntError;
@@ -105,6 +108,26 @@ println!("{:?}", res);
105108
# assert!(res.is_err())
106109
```
107110

111+
When applied to values of the `Option<T>` type, it propagates `Nones`. If the
112+
value is `None`, then it will return `None`. If applied to `Some(x)`, then it
113+
will unwrap the value to evaluate to `x`.
114+
115+
```rust
116+
fn try_option_some() -> Option<u8> {
117+
let val = Some(1)?;
118+
Some(val)
119+
}
120+
assert_eq!(try_option_some(), Some(1));
121+
122+
fn try_option_none() -> Option<u8> {
123+
let val = None?;
124+
Some(val)
125+
}
126+
assert_eq!(try_option_none(), None);
127+
```
128+
129+
`?` cannot be overloaded.
130+
108131
## Negation operators
109132

110133
These are the last two unary operators. This table summarizes the behavior of

0 commit comments

Comments
 (0)