Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- #[derive(Debug)]
- #[allow(dead_code)]
- struct Entry {
- id: u64,
- title: String,
- username: String,
- password: String,
- }
- #[derive(Debug)]
- #[allow(dead_code)]
- struct Group {
- name: String,
- groups: Vec<Group>,
- entries: Vec<Entry>,
- }
- #[derive(Debug)]
- struct Database<'a> {
- id_map: HashMap<u64, &'a Entry>,
- top: Group,
- }
- fn main() {
- let mut db = Database {
- top: Group {
- name: "Top-level".to_string(),
- groups: vec![
- Group {
- name: "Games".to_string(),
- groups: vec![],
- entries: vec![
- Entry {
- id: 23,
- title: "World of Warcraft".to_string(),
- username: "darkelf123".to_string(),
- password: "s3cr!t".to_string(),
- },
- ],
- },
- ],
- entries: vec![],
- },
- id_map: HashMap::new(),
- };
- db.id_map.insert(db.top.groups[0].entries[0].id, &db.top.groups[0].entries[0]);
- println!("Entry ID 23: {:#?}", db.id_map.get(&23));
- // Can no longer directly mutate entry:
- // let entry = &mut db.top.groups[0].entries[0];
- let mut entry = db.id_map.get_mut(&23).expect("Entry missing");
- // Can't modify entry through ID mapping
- // entry.username = "DarkElf123".to_string();
- }
Advertisement
Add Comment
Please, Sign In to add comment