lunes, 4 de septiembre de 2023

HashMap en Rust


Veamos un ejemplo: 


use std::collections::HashMap;

fn main() {

    let mut page_counts = HashMap::new();

    page_counts.insert("Adventures of Huckleberry Finn".to_string(), 207);

    page_counts.insert("Grimms' Fairy Tales".to_string(), 751);

    page_counts.insert("Pride and Prejudice".to_string(), 303);


    if !page_counts.contains_key("Les Misérables") {

        println!("We know about {} books, but not Les Misérables.",

                 page_counts.len());

    }


    for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] {

        match page_counts.get(book) {

            Some(count) => println!("{book}: {count} pages"),

            None => println!("{book} is unknown.")

        }

    }


    // Use the .entry() method to insert a value if nothing is found.

    for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] {

        let page_count: &mut i32 = page_counts.entry(book.to_string()).or_insert(0);

        *page_count += 1;

    }


    println!("{page_counts:#?}");

}


Si ejecutamos este programa: 

Finished dev [unoptimized + debuginfo] target(s) in 0.05s

     Running `target/debug/hello_cargo`

We know about 3 books, but not Les Misérables.

Pride and Prejudice: 303 pages

Alice's Adventure in Wonderland is unknown.

{

    "Pride and Prejudice": 304,

    "Grimms' Fairy Tales": 751,

    "Adventures of Huckleberry Finn": 207,

    "Alice's Adventure in Wonderland": 1,

}


HashMap no está definido por defecto y es necesario incluirlo : use std::collections::HashMap;

Desde Rust 1.56, HashMap implementa From<[(K, V); N]>, que nos permite inicializar fácilmente un mapa hash a partir de una matriz literal:

  let page_counts = HashMap::from([

    ("Harry Potter and the Sorcerer's Stone".to_string(), 336),

    ("The Hunger Games".to_string(), 374),

  ]);

Alternativamente, HashMap se puede construir a partir de cualquier iterador que produzca tuplas de valores clave.

Mostramos HashMap<String, i32> y evitamos usar &str como clave para facilitar los ejemplos. Por supuesto, se puede utilizar referencias en colecciones, pero puede generar complicaciones con el verificador de préstamos.

Podemos agregar estas lineas : 

  let pc1 = page_counts

      .get("Harry Potter and the Sorcerer's Stone ")

      .unwrap_or(&336);

  let pc2 = page_counts

      .entry("The Hunger Games".to_string())

      .or_insert(374);

La primera línea verá si un libro está en el HashMap y, en caso contrario, devolverá un valor alternativo. La segunda línea insertará el valor alternativo en el HashMap si no se encuentra el libro.

 


No hay comentarios.:

Publicar un comentario