Skip to content

Instantly share code, notes, and snippets.

@himat
Created December 16, 2020 19:51
Show Gist options
  • Save himat/ba96de32bfd51e06cdd2f3ab96562529 to your computer and use it in GitHub Desktop.
Save himat/ba96de32bfd51e06cdd2f3ab96562529 to your computer and use it in GitHub Desktop.
[Extract field inside of optional struct as an option] Use this when you want to extract a field from an optional struct and keep that field also as an option type #rust
struct User {
id: i32,
}
// fn do_something_with_user_id(Option<i32>);
// Bad, simple solution
fn something(user_option: Option<User>) {
let user_id_option = if let Some(user) = user_option { Some(user.id) } else { None };
do_something_with_user_id(user_id_option);
}
// Good, Elegant solution
// Option::map applies a function to the contained value only and leaves None as is
fn something(user_option: Option<User>) {
let user_id_option = user_option.map(|user| user.id);
do_something_with_user_id(user_id_option);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment