4

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'

1
  • 1
    iter over keys, then use the duplicate Commented Apr 9, 2019 at 14:40

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.