해쉬맵 HashMap(K, V)은 K 타입의 키에 V타입의 값을 매핑한 것을 저장합니다.
생성
해쉬맵은 std::collections::HashMap 모듈을 임포트 해서 사용할 수 있으며
String, Vector처럼 ::new를 통해 생성할 수 있습니다.
use std::collections::HashMap;
let mut scores = HashMap::new();
insert 메소드로 값을 저장할 수 있습니다.
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
벡터의 collect 메소드를 통해 해쉬맵을 생성할 수 도 있습니다.
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();
teams와 initial_scores라는 두 벡터에서 "Blue"의 초기 점수는 10 점이다 라는 것을 표현하기 위해 zip 메소드를 이용하여 "Blue"와 10이 한쌍인 튜플의 벡터를 생성하고 collect로 튜플의 벡터를 HashMap으로 바꿀 수 있습니다.
해쉬맵에 사용되는 키와 값은 삽입되는 순간 소유권이 해쉬맵으로 이전되어 사용할 수 없게 됩니다.
use std::collections::HashMap;
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
map.insert(field_name, field_value);
해쉬맵 내의 값 접근
해쉬맵 내의 값에 접근은 get 메소드를 사용하여 값을 얻어올 수 있습니다.
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);
해쉬맵의 get 메소드는 벡터의 get 처럼 Opton(&V)을 반환하기 때문에 값이 존재하지 않는다면 None을 반환합니다.
반복문을 사용한 접근 또한 가능합니다.
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);
}
해쉬맵 갱신하기
값 덮어쓰기
같은 키에 다른 값을 여러 번 삽입한다면 해쉬맵은 그 값의 가장 최근 값만을 가지고 있습니다.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{:?}", scores);
키에 할당된 값이 없을 경우에만 삽입하기
해쉬맵의 가지고 있는 entry라는 특별한 api를 이용하여 해쉬맵에 해당 키가 존재하지 않는다면 값을 삽입합니다.
entry의 반환 값은 해당 키가 존재한다면 그 키 값을 반환하고 존재하지 않는다면 값을 삽입하고 삽입한 값을 반환해줍니다.
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);
예전 값을 기초로 값을 수정하기
해쉬맵에 대한 또 다른 흔한 사용 방식은 키에 대한 값을 찾아서 예전 값에 기초하여 값을 수정하는 것입니다. 예를 들어, 어떤 텍스트 내에 각 단어가 몇 번이나 나왔는지를 세는 코드를 작성해보면. 해쉬맵을 이용하여 해당 단어가 몇번이나 나왔는지를 유지하기 위해 값을 증가시켜 줍니다. 만일 어떤 단어를 처음 본 것이라면, 값 0을 삽입할 것입니다.
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);
or_insert는 &mut V를 반환하기 때문에 count는 값을 수정하기 위해서 *로 역참조를 해야 합니다.
'Rust' 카테고리의 다른 글
[Rust] 제네릭(Generic) (0) | 2022.04.28 |
---|---|
[Rust] 벡터 (0) | 2022.04.27 |
[Rust] 문자열 (0) | 2022.04.25 |
[Rust] Option 과 Result (0) | 2022.04.25 |
[Rust] match 흐름 제어 연산자 (0) | 2022.04.24 |