官术网_书友最值得收藏!

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 230字
  • 2021-07-02 13:35:17

Hashmaps

Rust also provides us with maps, which can be used to store key-value data. They come from the std::collections module and are named HashMap. They are created with the HashMap::new constructor function:

// hashmaps.rs

use std::collections::HashMap;

fn main() {
let mut fruits = HashMap::new();
fruits.insert("apple", 3);
fruits.insert("mango", 6);
fruits.insert("orange", 2);
fruits.insert("avocado", 7);
for (k, v) in &fruits {
println!("I got {} {}", v, k);
}

fruits.remove("orange");
let old_avocado = fruits["avocado"];
fruits.insert("avocado", old_avocado + 5);
println!("\nI now have {} avocados", fruits["avocado"]);
}

In the preceding code, we created a new HashMap called fruits. We then insert some fruits into our fruits map, along with their count, using the insert method. Following that, we iterate over the key value pairs using for loop, where in we take a reference to our fruit map by &fruits, because we only want read access to the key and value. By default, the value will be consumed by the for loop. The for loop in this case returns a two field tuple ((k ,v)). There are also seperate methods keys() and values() available to iterate over just keys and values, respectively. The hashing algorithm used for hashing the keys of the HashMap type is based on the Robin hood open addressing scheme, but can be replaced with a custom hasher depending on the use case and performance. That's about it.

Next, let's look at slices.

主站蜘蛛池模板: 凤冈县| 搜索| 文安县| 云林县| 时尚| 盐山县| 彰武县| 花垣县| 米易县| 镇雄县| 弥勒县| 夏河县| 外汇| 同德县| 黄大仙区| 闸北区| 阳曲县| 平罗县| 曲松县| 锡林浩特市| 灌南县| 河北省| 合作市| 民权县| 明溪县| 平罗县| 绥宁县| 招远市| 达尔| 许昌市| 隆化县| 平阴县| 图片| 内黄县| 吴川市| 新巴尔虎右旗| 读书| 徐汇区| 江永县| 安新县| 郸城县|