Rust: 如何遍历Hashmap

下面展示一下如何使用 .iter()方法来打印 hashmap。

代码

use std::collections::HashMap;
 
fn print_hashmap(map: &mut HashMap<String, u8>) {
    
    
    for (key, value) in map.iter() {
    
    
        println!("{} / {}", key, value);
    }
}
 
fn main() {
    
    
    let mut hashmap: HashMap<String, u8> = HashMap::new();
    hashmap.insert("a".to_string(), 1);
    hashmap.insert("b".to_string(), 2);
    
    print_hashmap(&mut hashmap);
}

运行结果

在这里插入图片描述

Rust Playground link

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=82605cb826489c5ab6ba4659f464b5b1

欢迎关注我的公众号 夏虫不可语冰也
同时也欢迎访问我的个人网站 www.cjl946.com
PS:在浏览器中直接输入网址即可
夏虫不可语冰也

猜你喜欢

转载自blog.csdn.net/weixin_43616215/article/details/125659489