카테고리 없음

[Rust] Hash Map 예제 (18일차)

꾸압 2022. 12. 29. 23:44

 

<예제_1>

#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let teams = vec![String::from("Blue"), String::from("Yellow")];
    let initial_scores = vec![10, 50];

    let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
}

 


 

<예제_2>

#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let team_name = String::from("Blue");
    let score = scores.get(&team_name);

    println!("{:?}", &score);
}

 


 

<예제_3>

#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    for (key, value) in &scores {
        println!("{} : {}", key, value);
    }
}

 


 

<예제_4>

// key 값이 겹치면 기존 값을 덮어 씀
#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Blue"), 25);

    println!("{:?}", scores);
}

 


 

<예제_5>

// Key 할당값이 없으면 새로운 Value 넣기
#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);

    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);

    println!("{:?}", scores);
}

 

 


 

<예제_6>

// 예전 값을 기초로 Value 갱신
#![allow(unused)]
fn main() {
    use std::collections::HashMap;

    let text = "Hello World! Wonderful World!";

    let mut map = HashMap::new();

    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count += 1;
    }

    println!("{:?}", map);
}

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch08-03-hash-maps.html