0

I'm trying to get the keys of a BTreeMap with u32 keys.

When I use the .iter().keys() method, it returns a reference to the keys: &u32.

I understand the logic behind getting a reference to the key because it doesn't consume the data structure, but since u32 implements the Copy trait, I figured it is possible to get u32 directly.

The only way I found of doing this is by mapping over all the keys and dereferencing them:

let map = BTreeMap::from([
  (0, "foo"),
  (1, "bar"),
  (2, "baz")
])

let keys: Vec<u32> = map.iter().map(|(k, _)| *k).collect();

Is there a better, faster or more concise way of doing this?

1 Answers1

1

I suggest either

let keys = map.keys().copied().collect();

or if you don't need the map any more:

let keys = map.into_keys().collect();
cafce25
  • 15,907
  • 4
  • 25
  • 31
  • Thank you! Does the first option take longer since it iterates over the iterator twice? Is there some iterator magic going on that won't make it iterate twice? – Charles Edward Gagnon Nov 09 '22 at 14:29
  • 1
    Iterators are lazy meaning you only iterate once you repeatedly call `next` (possibly in a for-loop) or `collect` them or some other method that actually iterates so there is no multiple iterations in the first variant, only the final `collect`. That being said the first option has to copy all elements and thus is probably slightly slower, though i doub't you'll notice it in the real world. – cafce25 Nov 09 '22 at 21:00