Rust•HashMap
Rust の HashMap:キー・値ハッシュテーブルと Entry API
Rust の HashMap、get() による安全な参照、entry().or_insert() を使ったデフォルト値挿入を学びます。
構文
use std::collections::HashMap;
let mut map = HashMap::new();
map.entry("key").or_insert(10);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| entry().or_insert() | Entry API | キーが存在しない場合のみデフォルト値を挿入します。 |
そのまま実行できるコード例
Compilra で実行可能Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
use std::collections::HashMap;
fn main() {
let mut port_registry = HashMap::new();
port_registry.insert(String::from("HTTP"), 80);
port_registry.insert(String::from("HTTPS"), 443);
port_registry.insert(String::from("SSH"), 22);
// Entry API: Insert default if not present
port_registry.entry(String::from("REDIS")).or_insert(6379);
// Safe lookup with .get() returning Option<&V>
let protocol = "HTTPS";
match port_registry.get(protocol) {
Some(port) => println!("{} is bound to port {}", protocol, port),
None => println!("Protocol not found"),
}
println!("\nAll Ports:");
for (k, v) in &port_registry {
println!(" {} -> {}", k, v);
}
}期待される出力:
HTTPS is bound to port 443 All Ports: HTTP -> 80 HTTPS -> 443 SSH -> 22 REDIS -> 6379
動作のしくみ: ステップ解説
- 4-8 行目: HashMap を初期化し、キーと値のペアを挿入します。
- 11 行目: Entry API が 1 回の検索で "REDIS" -> 6379 を挿入します。
- 15-18 行目: .get() は Option<&i32> を返します。
重要ポイント
- HashMap のキーは Eq および Hash トレイトを実装している必要があります。
- Entry API は単一検索による安全な upsert セマンティクスを提供します。
よくある間違い: &str がそのまま使える場面で &String を使って検索しようとする
Deref coercion により HashMap<String, V>.get() は &str を直接受け取れます。String::from を確保する必要はありません。
❌ 誤り
map.get(&String::from("key")) // Unnecessary heap allocation!✅ 正しい例
map.get("key") // Clean &str lookup