study_rust_example/common_collection/
hash_map_study.rs1use std::collections::{hash_map, HashMap};
2
3#[derive(Eq, Hash, PartialEq, Debug)]
4enum CoinEnum {
5 BTC,
6 ETH,
7 USDT,
8}
9#[derive(Debug)]
10struct CoinProerty {
11 decimal: u32,
12}
13
14fn iterator_hash_map(map_val: &HashMap<CoinEnum, CoinProerty>) {
15 for (key, val) in map_val {
16 println!("key {:?} val {:?}", key, val);
17 }
18}
19
20fn count_text_num(str_val: &str, target: &str) -> u16 {
21 let mut count_map: HashMap<&str, u16> = HashMap::new();
22 for word in str_val.split_whitespace() {
23 let count = count_map.entry(word).or_insert(0);
24 *count += 1;
25 }
26 match count_map.get(target) {
27 None => 0,
28 Some(val) => *val,
29 }
30}
31
32pub fn hash_map_usage_study() {
33 let mut coinMap: HashMap<CoinEnum, CoinProerty> = HashMap::new();
34 coinMap.insert(CoinEnum::BTC, CoinProerty { decimal: 8 });
35 coinMap.insert(CoinEnum::ETH, CoinProerty { decimal: 9 });
36 coinMap.insert(CoinEnum::ETH, CoinProerty { decimal: 18 });
37 coinMap.insert(CoinEnum::USDT, CoinProerty { decimal: 6 });
38 coinMap
40 .entry(CoinEnum::USDT)
41 .or_insert(CoinProerty { decimal: (6) });
42 let coin = CoinEnum::ETH;
44 let eth_pro = coinMap.get(&coin);
45 println!();
46 println!("coin {:?}, pro {:?}", coin, eth_pro);
47 iterator_hash_map(&coinMap);
48 let text = "hello hello world rust people hello hello .";
49 let count = count_text_num(text, &text[..5]);
50 println!("word {} count {}", &text[..5], count);
51}