Skip to content

Instantly share code, notes, and snippets.

@CarterTsai
Last active April 11, 2020 17:09
Show Gist options
  • Save CarterTsai/ea1c0c01bccc7864512bc860115e5e90 to your computer and use it in GitHub Desktop.
Save CarterTsai/ea1c0c01bccc7864512bc860115e5e90 to your computer and use it in GitHub Desktop.
rust hashmap example
// https://learning-rust.github.io/docs/e4.unwrap_and_expect.html
use std::collections::HashMap;
fn main() {
// 範例一
let mut inventory = HashMap::new();
// 設定預設值
let inventory_default = 0;
// 加入資料到HashMap
inventory.insert(String::from("Notebook"), 10);
// 有符合的資料
println!("===== 範例一 =====");
println!(
"Exits 'Notebook' key : {}",
inventory
.get(&String::from("Notebook"))
.unwrap_or(&inventory_default)
);
// 沒有符合的資料
println!(
"No Exits 'PC' key : {}",
inventory
.get(&String::from("PC"))
.unwrap_or(&inventory_default)
);
// 範例二
let mut product_name = HashMap::new();
// 加入資料到HashMap
product_name.insert(
String::from("A100123"),
String::from("最新款筆記型電腦"),
);
// 設定預設值
let product_name_default = String::from("沒有找到任何產品");
println!("\n===== 範例二 =====");
// 有符合的資料
println!(
"Exits 'A100123' key : {}",
product_name.get(&String::from("A100123")).unwrap()
);
// 沒有符合的資料
println!(
"No Exits 'A99999' key {}",
product_name
.get(&String::from("A99999"))
.unwrap_or(&product_name_default)
);
// 範例三
let mut car_price = HashMap::new();
let car_name = vec![String::from("BMW"), String::from("Benz")];
// 加入資料到HashMap
car_price.insert(String::from("BMW"), String::from("NT1500,000"));
println!("\n===== 範例三 =====");
for _name in &car_name {
match car_price.get(_name) {
Some(price) => println!("{} Price {:?}", _name, price),
None => println!("{}找不到任何車款價格", _name),
}
}
// 範例四
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
println!("\n===== 範例四 =====");
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
println!("scores {:?}", scores);
// 範例五 在沒有key的狀況下 新增一筆資料
let mut board = HashMap::new();
board.insert(String::from("Yellow"), &99);
println!("\n===== 範例五 在沒有key的狀況下 新增一筆資料 =====");
println!("board entry before {:?}", board);
board.entry(String::from("Red")).or_insert(&50);
println!("board entry after {:?}", board);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment