Skip to content

Instantly share code, notes, and snippets.

@dzamkov

dzamkov/main.rs Secret

Last active January 17, 2022 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzamkov/e72f83f77d68321efe3c0e370fea1355 to your computer and use it in GitHub Desktop.
Save dzamkov/e72f83f77d68321efe3c0e370fea1355 to your computer and use it in GitHub Desktop.
use fortify::*;
use std::collections::HashMap;
#[derive(Debug)]
struct User {
pub name: String,
pub data: u32,
// ...
}
struct Config(Fortify<ConfigInner<'static>>);
#[derive(WithLifetime)]
struct ConfigInner<'a> {
pub users: &'a Vec<User>,
pub map: HashMap<&'a str, &'a User>,
}
impl Config {
pub fn new(users: Vec<User>) -> Self {
fn build_map<'a>(users: &'a Vec<User>) -> HashMap<&'a str, &'a User> {
let mut map = HashMap::new();
for user in users.iter() {
map.insert(user.name.as_str(), user);
}
map
}
Config(fortify! {
let users = users;
yield ConfigInner {
users: &users,
map: build_map(&users)
};
})
}
pub fn get_user_by_name(&self, name: &str) -> Option<&User> {
self.0.borrow().map.get(name).copied()
}
}
fn main() {
let config = Config::new(vec![
User {
name: "Alice".to_string(),
data: 24
},
User {
name: "Bob".to_string(),
data: 30
},
]);
println!("{:?}", config.get_user_by_name("Alice"));
println!("{:?}", config.get_user_by_name("Bob"));
println!("{:?}", config.get_user_by_name("Charlie"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment