如何解决Rust:如何将Entry API与拥有的数据结合起来?
我有一个HashMap
,想更新一个值(如果存在),否则添加一个默认值。通常我会这样:
some_map.entry(some_key)
.and_modify(|e| modify(e))
.or_insert(default)
但是现在我的modify
的类型为fn(T)->T
,但是借位检查器显然不允许我写:
some_map.entry(some_key)
.and_modify(|e| *e = modify(*e))
.or_insert(default)
在Rust中执行此操作的首选方式是什么?我应该只使用remove
和insert
吗?
解决方法
假设您可以便宜地创建T
的空版本,则可以使用mem::replace
:
some_map.entry(some_key)
.and_modify(|e| {
// swaps the second parameter in and returns the value which was there
let mut v = mem::replace(e,T::empty());
v = modify(v);
// puts the value back in and discards the empty one
mem::replace(e,v);
})
.or_insert(default)
这假设modify
不会出现恐慌,否则您将发现自己的“空”值保留在地图中。但是remove
/ insert
也会遇到类似的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。