Skip to content

Instantly share code, notes, and snippets.

@metatoaster
Last active May 26, 2023 23:51
Show Gist options
  • Save metatoaster/d232e3a14ef212f579322dd8ff479940 to your computer and use it in GitHub Desktop.
Save metatoaster/d232e3a14ef212f579322dd8ff479940 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
struct ListOfUsers(Vec<(String, String)>); // (User, Email)
struct UserToEmail<'a>(HashMap<&'a str, &'a str>);
struct EmailToUser<'a>(HashMap<&'a str, &'a str>);
impl<'a> From<&'a ListOfUsers> for UserToEmail<'a> {
fn from(value: &'a ListOfUsers) -> Self {
Self(value.0.iter()
.map(|(u, e)| (u.as_ref(), e.as_ref()))
.collect::<HashMap<&'_ str, &'_ str>>()
)
}
}
impl<'a> From<&'a ListOfUsers> for EmailToUser<'a> {
fn from(value: &'a ListOfUsers) -> Self {
Self(value.0.iter()
.map(|(u, e)| (e.as_ref(), u.as_ref()))
.collect::<HashMap<&'_ str, &'_ str>>()
)
}
}
fn main() {
let users = ListOfUsers(vec![
("John".into(), "[email protected]".into()),
("Mary".into(), "[email protected]".into()),
("Takao".into(), "[email protected]".into()),
("Darcy".into(), "[email protected]".into()),
]);
let user2email = UserToEmail::from(&users);
println!("{}", *user2email.0.get("Darcy").unwrap()); // [email protected]
let email2user = EmailToUser::from(&users);
println!("{}", *email2user.0.get("[email protected]").unwrap()); // Mary
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment