Tópicos importantes de Rust

Rust HashMap

Store values under keys and look them up fast: insert, get, entry and counting.

  • Avançado
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • insert and get
  • entry().or_insert()
  • Sorting the keys
stock
"apple"5
"pear"5
"plum"1

Values found by key

A HashMap<K, V> stores values under keys, so you can find a value quickly by its key. It is Rust's version of a dictionary or associative array.

insert adds or replaces a value. entry(key).or_insert(0) returns the existing value or inserts a default, which makes counting easy. get returns an Option because the key may be missing. A HashMap has no fixed order, so the keys are sorted before printing.

Pontos-chave

  1. get returns an Option: the key may be missing.
  2. entry(key).or_insert(0) is the counting pattern.
  3. A HashMap has no fixed order.

Exemplo executável de Rust

Rust
Executar código →
main.rs
use std::collections::HashMap;

fn main() {
    let mut stock: HashMap<String, u32> = HashMap::new();
    stock.insert(String::from("apple"), 3);
    stock.insert(String::from("pear"), 5);

    *stock.entry(String::from("apple")).or_insert(0) += 2;
    stock.entry(String::from("plum")).or_insert(1);

    println!("apples: {}", stock["apple"]);
    println!("has kiwi: {}", stock.contains_key("kiwi"));

    if let Some(count) = stock.get("pear") {
        println!("pears: {count}");
    }

    let mut names: Vec<&String> = stock.keys().collect();
    names.sort();
    println!("{:?}", names);
}
Gerar um botão Run para este exemplo Resultado da execução
apples: 5
has kiwi: false
pears: 5
["apple", "pear", "plum"]

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Word Frequency Counter →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios