代码:
use std::collections::{HashSet, HashMap}; fn main() { let mut set: HashSet<i32> = HashSet::new(); set.insert(1); set.insert(2); // 插入元素 // pub fn insert(&mut self, value: T) -> bool let is_insert_success = set.insert(3); println!("insert(3) => {}", is_insert_success); let re_check = set.insert(3); println!("insert(3) => {}", re_check); // 删除元素 // pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool let is_remove_success = set.remove(&3); println!("remove(3) => {}", is_remove_success); // 查询某个元素 // pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> let option = set.get(&1); println!("get(1) => {:?}", option); // 元素是否存在 // pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool let is_contains = set.contains(&1); println!("contains(1) => {}", is_contains); // 集合是否为空 // pub fn is_empty(&self) -> bool let is_empty = set.is_empty(); println!("is_empty() => {}", is_empty); // 集合中元素的个数 // pub fn len(&self) -> usize let size = set.len(); println!("len() => {}", size); // 清空集合 // pub fn clear(&mut self) set.clear(); let size = set.len(); println!("len() after clear() => {}", size); // hash-map + hash-set let mut map: HashMap<&str, HashSet<i32>> = HashMap::new(); let mut s1: HashSet<i32> = HashSet::new(); s1.insert(0); map.insert("s1", s1); let val = map.get(&"s1"); println!("set s1 => {:?}", val); match val { Some(s1) => println!("{}", s1.len()), None => todo!(), } }
标签:insert,set,HashSet,s1,示例,let,fn,println,Rust From: https://www.cnblogs.com/fanqshun/p/17066937.html