penguin359

Nested structures with quick-access index in Rust

Aug 28th, 2023
1,898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.50 KB | Source Code | 0 0
  1. use std::collections::HashMap;
  2.  
  3. #[derive(Debug)]
  4. #[allow(dead_code)]
  5. struct Entry {
  6.     id: u64,
  7.     title: String,
  8.     username: String,
  9.     password: String,
  10. }
  11.  
  12. #[derive(Debug)]
  13. #[allow(dead_code)]
  14. struct Group {
  15.     name: String,
  16.     groups: Vec<Group>,
  17.     entries: Vec<Entry>,
  18. }
  19.  
  20. #[derive(Debug)]
  21. struct Database<'a> {
  22.    id_map: HashMap<u64, &'a Entry>,
  23.     top: Group,
  24. }
  25.  
  26. fn main() {
  27.     let mut db = Database {
  28.         top: Group {
  29.             name: "Top-level".to_string(),
  30.             groups: vec![
  31.                 Group {
  32.                     name: "Games".to_string(),
  33.                     groups: vec![],
  34.                     entries: vec![
  35.                         Entry {
  36.                             id: 23,
  37.                             title: "World of Warcraft".to_string(),
  38.                             username: "darkelf123".to_string(),
  39.                             password: "s3cr!t".to_string(),
  40.                         },
  41.                     ],
  42.                 },
  43.             ],
  44.             entries: vec![],
  45.         },
  46.         id_map: HashMap::new(),
  47.     };
  48.  
  49.     db.id_map.insert(db.top.groups[0].entries[0].id, &db.top.groups[0].entries[0]);
  50.  
  51.     println!("Entry ID 23: {:#?}", db.id_map.get(&23));
  52.  
  53.     // Can no longer directly mutate entry:
  54.     // let entry = &mut db.top.groups[0].entries[0];
  55.  
  56.     let mut entry = db.id_map.get_mut(&23).expect("Entry missing");
  57.     // Can't modify entry through ID mapping
  58.     // entry.username = "DarkElf123".to_string();
  59. }
Tags: Question
Advertisement
Add Comment
Please, Sign In to add comment