@@ -84,13 +84,16 @@ let y = &mut 9;
84
84
assert_eq! (* y , 11 );
85
85
```
86
86
87
- ## The ` ? ` operator
87
+ ## The question mark operator
88
88
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 ` .
94
97
95
98
``` rust
96
99
# use std :: num :: ParseIntError ;
@@ -105,6 +108,26 @@ println!("{:?}", res);
105
108
# assert! (res . is_err ())
106
109
```
107
110
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
+
108
131
## Negation operators
109
132
110
133
These are the last two unary operators. This table summarizes the behavior of
0 commit comments