Last active
October 6, 2022 10:45
-
-
Save SteveLauC/fe0774604453c2b4d70ecbd611077664 to your computer and use it in GitHub Desktop.
Stupid code snippet to tell the diff between `map` and `and_then`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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