如何在 Rust 中循环字典对象?

Eka*_*Eka 0 dictionary loops hashmap rust

我有一本字典,在 python 中我可以使用它进行迭代

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

for i,j in data.items():
    print(i,j)
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用同一个对象并迭代 Rust 中的键和值吗?

Tey*_*dge 5

我假设您正在寻找一种在 Rust 中做到这一点的方法。

\n

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

\n

与Python的字典不同,HashMaps是静态类型的(即所有的键必须具有相同的类型,并且所有的值也必须共享相同的类型)\xe2\x80\x93\xc2\xa0来创建一个新的HashMap你想要的东西,例如:

\n
use std::collections::HashMap;\n\nfn main() {\n  let mut hashmap: HashMap<String, i32> = HashMap::new();\n  hashmap.insert("one".to_string(), 1);\n  for (key, value) in hashmap {\n      println!("{} {}", key, value);\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

哪个输出:

\n
one 1\n
Run Code Online (Sandbox Code Playgroud)\n

游乐场链接

\n

如果你想将 Python 中的对象加载到 Rust 中,有几个选项

\n
    \n
  • 您可以在Python进程中序列化该对象,然后使用serde在 Rust 端对其进行反序列化。

    \n
  • \n
  • 您可以绑定到 CPython(例如使用 PyO3)。

    \n
  • \n
\n