rust学习总结002

2022-11-16  本文已影响0人  球果假水晶蓝

rust 哈希表常用操作

use std::collections::HashMap;
let mut book_reviews = HashMap::new();
# 往哈希表添加元素
book_reviews.insert(
    "Adventures of Huckleberry Finn".to_string(),
    "My favorite book.".to_string(),
);
book_reviews.insert(
    "Grimms' Fairy Tales".to_string(),
    "Masterpiece.".to_string(),
);
# 检查哈希表是否含有key
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}
# 删除哈希表中key
book_reviews.remove("The Adventures of Sherlock Holmes");

// Look up the values associated with some keys.
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for &book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{book}: {review}"),
        None => println!("{book} is unreviewed.")
    }
}
# 访问keys
println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);

// Iterate over everything. 迭代访问
for (book, review) in &book_reviews {
    println!("{book}: \"{review}\"");
}
# 从数组中更新哈希表
let solar_distance = HashMap::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
    ("Earth", 1.0),
    ("Mars", 1.5),
]);


let mut player_stats = HashMap::new();
fn random_stat_buff() -> u8 {
    // could actually return some random value here - let's just return
    // some fixed value for now
    42
}

// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);

// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("defence").or_insert_with(random_stat_buff);

// update a key, guarding against the key possibly not being set
let stat = player_stats.entry("attack").or_insert(100);
*stat += random_stat_buff();

// modify an entry before an insert with in-place mutation
player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
use std::collections::HashMap;

fn main() {
  let keys = vec!["age", "size"];
  let values = vec![24, 12];

  let new_map: HashMap<_, _> = keys.iter().zip(values.iter()).collect();

  println!("{:?}", new_map); // {"age": 24, "size": 12}

  println!("{}", new_map[&"size"]); // 12

  match new_map.get(&"age") {
      Some(v) => println!("{}", v), // 24
      None => println!("None")
  }
}

获取 HashMap 成员

hashMap[key]
hashMap.get(key)

use std::collections::HashMap;

fn main() {
  let keys = vec!["age", "size"];
  let values = vec![24, 12];

  let new_map: HashMap<_, _> = keys.iter().zip(values.iter()).collect();

  println!("{:?}", new_map); // {"age": 24, "size": 12}

  println!("{}", new_map[&"size"]); // 12

  match new_map.get(&"age") {
      Some(v) => println!("{}", v), // 24
      None => println!("None")
  }
}
上一篇 下一篇

猜你喜欢

热点阅读