如何在锈中遍历字典对象? [英] How to loop through dictionary objects in rust?

查看:54
本文介绍了如何在锈中遍历字典对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,可以在python中使用

I have a dictionary which in python I can iterate using

data = {"one":1,"two":2,"three":3,"four":4,....."two hundred":200}

for i,j in data.items():
    print(i,j)

有什么办法可以使用同一个对象并遍历rust中的键和值?

Is there any way I can use the same object and iterate over the keys and values in rust?

推荐答案

我假设您正在寻找一种在Rust中进行此操作的方法.

I'm assuming you're after a way to do this in Rust.

Rust与Python词典的类似物是 HashMap .

Rust's analogue to a Python dictionary is a HashMap.

与Python的字典不同, HashMap 是静态类型的-要创建新的 HashMap ,您需要以下内容:

Unlike Python's dictionaies HashMaps are statically typed – to create a new HashMap you want something like:

use std::collections::HashMap;
fn main() {
  let mut hashmap: HashMap<String, i32> = HashMap::new();
  hashmap.insert("one".to_string(), 1);
  for (key, value) in hashmap {
      println!("{} {}", key, value);
  }
}

哪个输出:

one 1

游乐场链接

如果要将对象从Python加载到Rust中,则可以选择!

If you want to load the object from Python into Rust, you have options!

  • You can serialize (maybe as JSON?) from Python and then use serde to deserialize it on the Rust side. You would probably use a shell to pipe the output of the Python program to the Rust one.

您可以绑定到CPython(例如,使用PyO3).

You can bind to CPython (e.g. using PyO3).

这篇关于如何在锈中遍历字典对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆