Rewrite null-style is_none and unwrap checks with Option combinators
email_domain returns the domain of a user's email, or unknown when the user, the email or the @ is missing. Today its body tests is_none() before each step and calls unwrap() after it. Write the body again as a chain.
Constraints:
- no
unwrap,expect,is_some,is_none,matchorif letinemail_domain; - use
Optioncombinators; the?operator in a helper that returnsOption<String>is fine too; email_domain(1)givesexample.com; ids 2, 3 and 4 giveunknown.
fn find_user(id: u32) -> Option<&'static str> {
match id {
1 => Some("ann"),
2 => Some("bob"),
3 => Some("eve"),
_ => None,
}
}
fn email_of(name: &str) -> Option<String> {
match name {
"ann" => Some(String::from("ann@example.com")),
"bob" => Some(String::from("bob.at.home")),
_ => None,
}
}
fn email_domain(id: u32) -> String {
// your code here
}Write the implementation.
Each is_none test plus unwrap becomes a step of a chain: and_then for a step that can itself give None (the email, the @), map for one that cannot, and unwrap_or_else for the fallback. A helper using ? returns the same Option.
- Using
mapfor a step that itself returns anOption, which yieldsOption<Option<T>> - Applying
?to anOptioninside a function that returnsStringrather thanOption - Writing
unwrap_or(expensive()), whose argument is computed even when the value isSome
- How would you return a
Resultthat names the failed step, usingok_or? - Why does
unwrap_or_elsetake a closure whileunwrap_ortakes a value?
The chain repeats the steps of the original code, but the Option methods themselves take over the None checks:
fn find_user(id: u32) -> Option<&'static str> {
match id {
1 => Some("ann"),
2 => Some("bob"),
3 => Some("eve"),
_ => None,
}
}
fn email_of(name: &str) -> Option<String> {
match name {
"ann" => Some(String::from("ann@example.com")),
"bob" => Some(String::from("bob.at.home")),
_ => None,
}
}
fn email_domain(id: u32) -> String {
find_user(id)
.and_then(email_of)
.and_then(|email| email.split_once('@').map(|(_, domain)| domain.to_string()))
.unwrap_or_else(|| String::from("unknown"))
}
fn domain(id: u32) -> Option<String> {
let email = email_of(find_user(id)?)?;
let (_, domain) = email.split_once('@')?;
Some(domain.to_string())
}
fn main() {
for id in 1..=4 {
println!("{} {:?}", email_domain(id), domain(id));
}
}The program prints example.com Some("example.com") and then unknown None three times.
and_then(email_of)is a step that can itself returnNone(evehas no email). Withmapit would give anOption<Option<String>>.split_once('@')returns anOptiontoo, so it isand_thenagain; turning the&strinto aStringcannot fail, somapis enough for it.- Once a step gives
None, the rest do not run: for id 4,email_ofis never even called. unwrap_or_elsecomputes the fallback only onNone;unwrap_or(String::from("unknown"))would build the string on every call.
The ? version fits when the function itself returns an Option: domain reads like straight-line code, and the caller decides what to do with None, for example domain(id).unwrap_or_else(|| String::from("unknown")).