Converts from &Option<T>
to Option<&T>
.
Converts an Option<String>
into an Option<usize>
, preserving\nthe original. The map
method takes the self
argument by value, consuming the original,\nso this technique uses from
to first take an Option
to a reference\nto the value inside the original.
let s: Option<String> = Some(String::from(\"Hello, Rustaceans!\"));\nlet o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());\n\nprintln!(\"Can still print s: {s:?}\");\n\nassert_eq!(o, Some(18));
Takes each element in the Iterator
: if it is None
,\nno further elements are taken, and the None
is\nreturned. Should no None
occur, a container of type\nV
containing the values of each Option
is returned.
Here is an example which increments every integer in a vector.\nWe use the checked variant of add
that returns None
when the\ncalculation would result in an overflow.
let items = vec![0_u16, 1, 2];\n\nlet res: Option<Vec<u16>> = items\n .iter()\n .map(|x| x.checked_add(1))\n .collect();\n\nassert_eq!(res, Some(vec![1, 2, 3]));
As you can see, this will return the expected, valid items.
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet items = vec![2_u16, 1, 0];\n\nlet res: Option<Vec<u16>> = items\n .iter()\n .map(|x| x.checked_sub(1))\n .collect();\n\nassert_eq!(res, None);
Since the last element is zero, it would underflow. Thus, the resulting\nvalue is None
.
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first None
.
let items = vec![3_u16, 2, 1, 10];\n\nlet mut shared = 0;\n\nlet res: Option<Vec<u16>> = items\n .iter()\n .map(|x| { shared += x; x.checked_sub(2) })\n .collect();\n\nassert_eq!(res, None);\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.