Rust 주요 주제

Rust HashMap

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

  • 고급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

  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.

실행 가능한 Rust 예제

Rust
코드 실행 →
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);
}
이 예제의 실행 버튼 만들기 코드 실행 결과
apples: 5
has kiwi: false
pears: 5
["apple", "pear", "plum"]

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Word Frequency Counter →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지