3

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'

kabikaj
  • 43
  • 5

1 Answers1

5

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
belst
  • 2,285
  • 2
  • 20
  • 22