温馨提示×

rust set 如何使用

小樊
135
2024-12-06 21:29:19
栏目: 编程语言

在 Rust 中,Set 是一种无序且不包含重复元素的数据结构

首先,确保你已经安装了 Rust。如果没有,请访问 Rust 官方网站 并按照说明进行安装。

接下来,创建一个新的 Rust 项目:

cargo new set_example cd set_example 

现在,打开 src/main.rs 文件并编辑它,以便使用 Set。这是一个简单的示例:

use std::collections::HashSet; fn main() { // 创建一个空的 HashSet let mut my_set = HashSet::new(); // 向 HashSet 中添加元素 my_set.insert(1); my_set.insert(2); my_set.insert(3); my_set.insert(2); // 重复的元素,不会被添加到 HashSet 中 // 检查元素是否存在于 HashSet 中 if my_set.contains(&1) { println!("1 is in the set"); } else { println!("1 is not in the set"); } if my_set.contains(&4) { println!("4 is in the set"); } else { println!("4 is not in the set"); } // 遍历 HashSet println!("HashSet contains:"); for element in &my_set { println!("{}", element); } } 

在这个示例中,我们首先导入了 HashSet 类型,然后创建了一个名为 my_set 的可变 HashSet。接下来,我们向 my_set 中添加了一些元素,包括一个重复的元素(2)。然后,我们使用 contains 方法检查元素是否存在于 my_set 中,并使用 for 循环遍历 my_set 中的所有元素。

要运行此示例,请在终端中输入以下命令:

cargo run 

输出应该类似于以下内容:

1 is in the set 4 is not in the set HashSet contains: 1 2 3 

0