HashMap 만들기
키로 삽입하고 조회해 보세요.
HashMap 만들기은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is a HashMap?
A HashMap stores data as key-value pairs. You look things up by key instead of by index.
Think of a phone book: a name (key) maps to a number (value). HashMaps are perfect when you need fast lookups by a meaningful key.
Importing HashMap
Unlike Vec and String, HashMap is not in the prelude. You must bring it into scope.
Add a use line at the top of your file. This makes the name available throughout the module.
use std::collections::HashMap;
fn main() {
let scores: HashMap<String, i32> = HashMap::new();
println!("empty map len: {}", scores.len());
}Inserting Pairs
Use insert to add a key and its value. If the key already exists, the old value is replaced.
The map must be declared mut to allow insertion.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 50);
scores.insert("Bob", 30);
println!("{} players", scores.len());
}Type Inference
You rarely need to write the type. Rust infers HashMap<&str, i32> from the first insert calls.
Here the keys are string slices and the values are integers, all decided by usage.
use std::collections::HashMap;
fn main() {
let mut ages = HashMap::new();
ages.insert("Sam", 28);
ages.insert("Mia", 34);
println!("Sam is {}", ages["Sam"]);
}Getting Values
The get method returns an Option. You get Some(&value) if the key exists, or None if it does not.
This forces you to handle the missing case safely.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 50);
match scores.get("Alice") {
Some(v) => println!("score: {}", v),
None => println!("no score"),
}
}Indexing vs get
You can index with map[key], but it panics if the key is missing.
Prefer get when a key might not exist. Use indexing only when you are certain the key is present.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert("x", 1);
// m["y"] would panic!
let v = m.get("y").copied().unwrap_or(0);
println!("y = {}", v);
}Updating a Value
Calling insert with an existing key overwrites the old value.
The previous value is returned (wrapped in Option) so you can inspect it if you like.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert("k", 1);
let old = m.insert("k", 9);
println!("old = {:?}, now = {}", old, m["k"]);
}Checking Keys
Use contains_key to test whether a key exists without retrieving its value.
It returns a plain bool, which is handy in if conditions.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert("on", true);
if m.contains_key("on") {
println!("key exists");
}
}Removing Entries
The remove method deletes a key and returns its value as an Option.
If the key was not present you get None, so removal is always safe.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert("a", 1);
let removed = m.remove("a");
println!("removed {:?}, len {}", removed, m.len());
}Iterating Over a Map
A for loop over a HashMap yields (key, value) tuples by reference.
Note the order is unspecified and may change between runs, since hashing scrambles placement.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert("a", 1);
m.insert("b", 2);
for (k, v) in &m {
println!("{} -> {}", k, v);
}
}Ownership of Keys
When you insert owned values like a String, the map takes ownership.
After insertion you cannot use that variable again unless you cloned it first.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
let name = String::from("Alice");
m.insert(name, 50);
// name is moved here; m owns it now
println!("{}", m["Alice"]);
}Quick Check
You want a value but the key might be missing.
Recap
You learned to create a HashMap, insert pairs, and look up values with get or indexing.
You also saw contains_key, remove, iteration, and how the map takes ownership of inserted keys.
자주 묻는 질문
“HashMap 만들기” 강의는 무료인가요?
네 — “HashMap 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
“HashMap 만들기”에서 뭘 배우나요?
키로 삽입하고 조회해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“HashMap 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- HashMap 만들기
- Entry API와 기본값
- HashSet 다루기
- 개수 세기와 그룹화