0
点赞
收藏
分享

微信扫一扫

rust 在 Vec 中存储不同类型的元素

Vec 中的元素必须是相同的类型,例如以下代码会发生错误:

fn main() {

let v = vec![1, 2.0, 3];

}

但是我们可以使用枚举或特征对象来存储不同的类型.

7. 🌟🌟

#[derive(Debug)]

enum IpAddr {

V4(String),

V6(String),

}

fn main() {

// 填 空

let v : Vec<IpAddr>= __;

// 枚 举 的 比 较 需 要 派 生 PartialEq 特 征

assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));

assert_eq!(v[1], IpAddr::V6("::1".to_string()));

println!("Success!")

}

8. 🌟🌟

trait IpAddr {

fn display(&self);

}

struct V4(String);

impl IpAddr for V4 {

fn display(&self) {

println!("ipv4: {:?}",self.0)

}

}

struct V6(String);

impl IpAddr for V6 {

fn display(&self) {

println!("ipv6: {:?}",self.0)

}

}

fn main() {

// 填 空

let v: __= vec![

Box::new(V4("127.0.0.1".to_string())),

Box::new(V6("::1".to_string())),

];

for ip in v {

ip.display();

}

}

HashMap

HashMap 默认使用 SipHash 1-3 哈希算法,该算法对于抵抗 HashDos非常有效。在性能方面,如

果你的 key 是中型大小的,那该算法非常不错,但是如果是小型的 key( 例如整数 )亦或是大型的 key ( 例如

字符串 ),那你需要采用社区提供的其它算法来提高性能。

哈希表的算法是基于 Google 的 SwissTable,你可以在这里找到 C++ 的实现,同时在 CppCon talk 上也有

关于算法如何工作的演讲。

基本操作

1. 🌟🌟

// 填 空 并 修 复 错 误

use std::collections::HashMap;

fn main() {

let mut scores = HashMap::new();

scores.insert("Sunface", 98);

scores.insert("Daniel", 95);

scores.insert("Ashley", 69.0);

scores.insert("Katie", "58");

// get 返 回 一 个 Option<&V> 枚 举 值

let score = scores.get("Sunface");

assert_eq!(score, Some(98));

if scores.contains_key("Daniel") {

// 索 引 返 回 一 个 值 V

let score = scores["Daniel"];

assert_eq!(score, __);

scores.remove("Daniel");

}

assert_eq!(scores.len(), __);

for (name, score) in scores {

println!("The score of {} is {}", name, score)

}

}

2. 🌟🌟

use std::collections::HashMap;

fn main() {

let teams = [

("Chinese Team", 100),

("American Team", 10),

("France Team", 50),

];

let mut teams_map1 = HashMap::new();

for team in &teams {

teams_map1.insert(team.0, team.1);

}

// 使 用 两 种 方 法 实 现 team_map2

// 提 示:其 中 一 种 方 法 是 使 用 `collect` 方 法

let teams_map2...

assert_eq!(teams_map1, teams_map2);

println!("Success!")

}

3. 🌟🌟

// 填 空

use std::collections::HashMap;

fn main() {

// 编 译 器 可 以 根 据 后 续 的 使 用 情 况 帮 我 自 动 推 断 出 HashMap 的 类 型 , 当 然 你 也 可 以 显 式 地 标 注 类

let mut player_stats = HashMap::new();

// 查 询 指 定 的 key, 若 不 存 在 时 , 则 插 入 新 的 kv 值

player_stats.entry("health").or_insert(100);

assert_eq!(player_stats["health"], __);

// 通 过 函 数 来 返 回 新 的 值

player_stats.entry("health").or_insert_with(random_stat_buff);

assert_eq!(player_stats["health"], __);

let health = player_stats.entry("health").or_insert(50);

assert_eq!(health, __);

*health -= 50;

assert_eq!(*health, __);

println!("Success!")

}

fn random_stat_buff() -> u8 {

// 为 了 简 单 , 我 们 没 有 使 用 随 机 , 而 是 返 回 一 个 固 定 的 值

42

}

举报

相关推荐

0 条评论