Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 7, 2024 12:35
Show Gist options
  • Save max-itzpapalotl/7a75ffdf88fe5131c897ec219d119152 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/7a75ffdf88fe5131c897ec219d119152 to your computer and use it in GitHub Desktop.
8. HashMaps

8. HashMaps

  • Construction, insertion
  • Lookup, deletion
  • Matching
  • HashMap literals

Construction, insertion

use std::collections::HashMap;

fn main() {
    let mut m : HashMap<String, u64> = HashMap::new();
    m.insert("abc".to_string(), 12);
    m.insert("xyz".to_string(), 13);
    println!("{:?}", m);
}
use std::collections::HashMap;

fn main() {
    let mut m : HashMap<String, u64> = HashMap::with_capacity(3);
    m.insert("abc".to_string(), 12);
    m.insert("xyz".to_string(), 13);
    println!("{:?}", m);
}
use std::collections::HashMap;

fn main() {
    let mut m : HashMap<String, u64> = HashMap::with_capacity(3);
    let x = m.insert("abc".to_string(), 12);
    println!("{:?}", x);
    m.insert("xyz".to_string(), 13);
    let y = m.insert("abc".to_string(), 13);
    println!("{:?}", y);
    println!("{:?}", m);
}

Lookup, deletion

use std::collections::HashMap;

fn main() {
    let mut m : HashMap<String, u64> = HashMap::new();
    m.insert("abc".to_string(), 12);
    m.insert("xyz".to_string(), 13);
    println!("{:?}", m);
    let key = "abc".to_string();
    let x = m.get(&key);
    println!("{:?}", x);
    let y = m.remove(&key);
    println!("{:?}", y);
    println!("{:?}", m);
    let x = m.get(&key);
    println!("{:?}", x);
}

Matching

use std::collections::HashMap;

fn main() {
    let mut m : HashMap<String, u64> = HashMap::new();
    m.insert("abc".to_string(), 12);
    m.insert("xyz".to_string(), 13);
    println!("{:?}", m);

    let key = "abc".to_string();
    let x = m.get(&key);
    match x {
        Some(xx) => println!("Found {}", xx),
        None => println!("Not found!"),
    };

    let y = m.remove(&key);
    println!("{:?}", y);
    println!("{:?}", m);

    let x = m.get(&key);
    match x {
        Some(xx) => println!("Found {}", xx),
        None => println!("Not found!"),
    };
}

HashMap literals

use std::collections::HashMap;

fn main() {
    let m = HashMap::from([("abc".to_string(), 12), ("xyz".to_string(), 13)]);      println!("{:?}", m);
}

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment