summaryrefslogtreecommitdiffstats
path: root/src/doc/rust-by-example/src/error/multiple_error_types/option_result.md
diff options
context:
space:
mode:
Diffstat (limited to 'src/doc/rust-by-example/src/error/multiple_error_types/option_result.md')
-rw-r--r--src/doc/rust-by-example/src/error/multiple_error_types/option_result.md56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/doc/rust-by-example/src/error/multiple_error_types/option_result.md b/src/doc/rust-by-example/src/error/multiple_error_types/option_result.md
new file mode 100644
index 000000000..d2273f698
--- /dev/null
+++ b/src/doc/rust-by-example/src/error/multiple_error_types/option_result.md
@@ -0,0 +1,56 @@
+# Pulling `Result`s out of `Option`s
+
+The most basic way of handling mixed error types is to just embed them in each
+other.
+
+```rust,editable
+use std::num::ParseIntError;
+
+fn double_first(vec: Vec<&str>) -> Option<Result<i32, ParseIntError>> {
+ vec.first().map(|first| {
+ first.parse::<i32>().map(|n| 2 * n)
+ })
+}
+
+fn main() {
+ let numbers = vec!["42", "93", "18"];
+ let empty = vec![];
+ let strings = vec!["tofu", "93", "18"];
+
+ println!("The first doubled is {:?}", double_first(numbers));
+
+ println!("The first doubled is {:?}", double_first(empty));
+ // Error 1: the input vector is empty
+
+ println!("The first doubled is {:?}", double_first(strings));
+ // Error 2: the element doesn't parse to a number
+}
+```
+
+There are times when we'll want to stop processing on errors (like with
+[`?`][enter_question_mark]) but keep going when the `Option` is `None`. A
+couple of combinators come in handy to swap the `Result` and `Option`.
+
+```rust,editable
+use std::num::ParseIntError;
+
+fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
+ let opt = vec.first().map(|first| {
+ first.parse::<i32>().map(|n| 2 * n)
+ });
+
+ opt.map_or(Ok(None), |r| r.map(Some))
+}
+
+fn main() {
+ let numbers = vec!["42", "93", "18"];
+ let empty = vec![];
+ let strings = vec!["tofu", "93", "18"];
+
+ println!("The first doubled is {:?}", double_first(numbers));
+ println!("The first doubled is {:?}", double_first(empty));
+ println!("The first doubled is {:?}", double_first(strings));
+}
+```
+
+[enter_question_mark]: ../result/enter_question_mark.md