Skip to content

Instantly share code, notes, and snippets.

@SteveLauC
Last active October 6, 2022 10:45
Show Gist options
  • Save SteveLauC/fe0774604453c2b4d70ecbd611077664 to your computer and use it in GitHub Desktop.
Save SteveLauC/fe0774604453c2b4d70ecbd611077664 to your computer and use it in GitHub Desktop.
Stupid code snippet to tell the diff between `map` and `and_then`
fn map_using_if<T, U, F>(s: Option<T>, f: F) -> Option<U>
where
F: FnOnce(T) -> U,
{
if let Some(item) = s {
Some(f(item))
} else {
None
}
}
fn and_then_using_if<T, U, F>(s: Option<T>, f: F) -> Option<U>
where
F: FnOnce(T) -> Option<U>,
{
if let Some(item) = s {
let res_of_f = f(item);
if let Some(val) = res_of_f {
Some(val)
} else {
None
}
} else {
None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment