-
-
Save dzamkov/e72f83f77d68321efe3c0e370fea1355 to your computer and use it in GitHub Desktop.
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
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