如何在锈中遍历字典对象? [英] How to loop through dictionary objects in rust?
问题描述
我有一本字典,可以在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 HashMap
s 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!
-
您可以从Python进行序列化(也许是JSON吗?),然后使用
serde
在Rust方面反序列化它.您可能会使用外壳将Python程序的输出通过管道传递到Rust上.
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屋!