Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a string joining the keys of a hashmap in rust [duplicate]

Tags:

rust

How can a create a string joining all keys of a hashmap in rust and adding a separator among each of them? I am very new to rust.

In python it would be something like this:

>>> ', '.join({'a':'x', 'b':'y'}.keys()) 'a, b'

like image 336
kabikaj Avatar asked Sep 06 '25 17:09

kabikaj


1 Answers

In Rust, HashMaps are not ordered, so the actual order of the keys in the String will be undefined.

If that is not a problem, you could do it like this:

use std::collections::HashMap;

let mut hm = HashMap::new();

hm.insert("a", ());
hm.insert("b", ());
hm.insert("c", ());
hm.insert("d", ());
hm.insert("e", ());

let s = hm.keys().map(|s| &**s).collect::<Vec<_>>().join(", ");

Playground

like image 68
belst Avatar answered Sep 10 '25 14:09

belst