Options
Type
Optionrepresents an optional value: every Option is eitherSomeand contains a value, orNone.enum Option<T> { Some(T), None, }The
if letsyntax lets you combineifandletinto a less verbose way to handle values that match one pattern while ignoring the rest.Using
if letmeans less typing, less indentation, and less boilerplate code.Similarly
while letsyntax lets you combinewhileandlet.
options1.rs
// This function returns how much icecream there is left in the fridge.
// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00,
// someone eats it all, so no icecream is left (value 0). Return `None` if
// `hour_of_day` is higher than 23.
fn maybe_icecream(hour_of_day: u16) -> Option<u16> {
// Complete the function body.
match hour_of_day {
0..=21 => Some(5),
22..=23 => Some(0),
_ => None,
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_value() {
// Fix this test. How do you get the value contained in the
// Option?
let icecreams = maybe_icecream(12).unwrap();
assert_eq!(icecreams, 5); // Don't change this line.
}
#[test]
fn check_icecream() {
assert_eq!(maybe_icecream(0), Some(5));
assert_eq!(maybe_icecream(9), Some(5));
assert_eq!(maybe_icecream(18), Some(5));
assert_eq!(maybe_icecream(22), Some(0));
assert_eq!(maybe_icecream(23), Some(0));
assert_eq!(maybe_icecream(24), None);
assert_eq!(maybe_icecream(25), None);
}
}In this exercise we need to return ice cream left by given hour.
Hour
0until21return5scoop left.Hour
22until23return0scoop left.Hour
24or more returnNone.
So based on the condition above we can use
matchsyntax like this:And to get the value we can use
unwrapmethod.unwrapcan cause panic if the values isNoneso best not to use, we can useunwrap_orinstead to provide default value ifNone.
options2.rs
In this exercise we need to fix
simple_optionfunction by usingif letsyntax to safely unwrap/unpack theOptionvalue.The code above will unwrap the
optional_target.If there is
Somevalue it will bind it to variablewordand we can use it inside the block.If
Nonethen it will ignore it.
Second task is to fix
simple_optionby usingwhile letsyntax.The code above will do same thing with
if let, it will check the returned value ofoptional_integers.pop().If there is
Somevalue there it will bind it tointegervariable and then goes inside the block.If
Nonethe loop will stop.
options3.rs
In this exercise because we want to use the variables
optional_pointfurther after match we should not move the ownership.Instead we should match the reference so it can be borrowed by adding
&.
Last updated