美文网首页
rust学习总结002

rust学习总结002

作者: 球果假水晶蓝 | 来源:发表于2022-11-16 22:40 被阅读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")
  }
}

相关文章

  • rust学习总结002

    rust 哈希表常用操作 获取 HashMap 成员 hashMap[key]hashMap.get(key)

  • rust基础学习总结

    1,对象实现Clone等接口 impl Clone for Obj { fn clone(&self)->Se...

  • rust学习总结-3

    _占位符 忽略该值或者类型,类似go中的 使用下划线开头忽略未使用的变量, 不会产生警告 _x 仍会将值绑定到变量...

  • rust学习总结-4

    Vector 动态数组类型用Vec 访问元素,确保索引不会越界的时候,就用索引访问,否则用 .get(索引超...

  • rust学习总结-1

    安装 install[https://www.rust-lang.org/zh-CN/tools/install]...

  • rust学习总结-2

    声明变量 let 可变性 默认不可变mut 修饰可变 变量遮蔽(shadowing) Rust 允许声明相同的变量...

  • rust学习总结001

  • 二零一七年二月

    技术 Rust 中文WikiRust PlaygroundRust学习资源和路线Rust in Detail: W...

  • Rust从安装到语法基础

    rust学习资源 rust中文网[https://www.rust-lang.org/zh-CN/]通过例子学ru...

  • windows环境安装Rust

    笔者之前一直是做前端开发,最近准备开始学习Rust,Rust的好处很多网上很多文章都有介绍,而且Rust非常适合作...

网友评论

      本文标题:rust学习总结002

      本文链接:https://www.haomeiwen.com/subject/zqpexdtx.html