从映射中获取取消引用的键

问题描述 投票:0回答:2

我正在尝试使用

BTreeMap
键获取
u32
的键。

当我使用

.iter().keys()
方法时,它返回对键的引用:
&u32

我理解获取密钥引用背后的逻辑,因为它不消耗数据结构,但由于

u32
实现了
Copy
特性,我认为可以直接获取
u32

我发现这样做的唯一方法是映射所有键并取消引用它们:

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

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

有更好、更快或更简洁的方法吗?

rust iterator btreemap
2个回答
1
投票

我建议要么

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

或者如果您不再需要地图:

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

0
投票

cafce25 的答案对我来说不起作用。这些键是字符串而不是 u32。我收到此错误:

error[E0277]: the trait bound `std::string::String: std::marker::Copy` is not satisfied
    --> src\operations_handler.rs:387:52
     |
387  |         let docx_ids_in_index = docx_hit_objs_map.keys().copied().collect();
     |                                                          ^^^^^^ the trait `std::marker::Copy` is not implemented for `std::string::String

这似乎可以作为替代方案:

let keys = map.keys().clone();

...它可能适用于 u32。

© www.soinside.com 2019 - 2024. All rights reserved.