修改 HashMap 中条目的值的正确方法是什么?
我是 Rust 的初学者,我还没有完成这本书,但有一件事让我问了这个问题。
考虑这段代码:
fn main() {
let mut entries = HashMap::new();
entries.insert("First".to_string(), 10);
entries.entry("Second".to_string()).or_insert(20);
assert_eq!(10, *entries.get("First").unwrap());
entries.entry(String::from("First")).and_modify(|value| { *value = 20});
assert_eq!(20, *entries.get("First").unwrap());
entries.insert("First".to_string(), 30);
assert_eq!(30, *entries.get("First").unwrap());
}
我使用了两种修改条目的方法:
entries.entry(String::from("First")).and_modify(|value| { *value = 20});
entries.insert("First".to_string(), 30);
insert
方式看起来很笨拙,而且我个人并没有使用它来修改条目中的值,但是......它有效。然而,除了语义之外,还有其他理由不使用它吗?正如我所说,我宁愿使用 entry
构造,而不仅仅是使用 insert
和现有密钥来暴力破解更新。像我这样的 Rustacean 新手不可能知道什么?
I am a beginner in Rust, I haven't finished the "Book" yet, but one thing made me ask this question.
Considering this code:
fn main() {
let mut entries = HashMap::new();
entries.insert("First".to_string(), 10);
entries.entry("Second".to_string()).or_insert(20);
assert_eq!(10, *entries.get("First").unwrap());
entries.entry(String::from("First")).and_modify(|value| { *value = 20});
assert_eq!(20, *entries.get("First").unwrap());
entries.insert("First".to_string(), 30);
assert_eq!(30, *entries.get("First").unwrap());
}
I have used two ways of modifying an entry:
entries.entry(String::from("First")).and_modify(|value| { *value = 20});
entries.insert("First".to_string(), 30);
The insert
way looks clunkish, and I woundn't personally use it to modify a value in an entry, but... it works. Nevertheless, is there a reason not to use it other than semantics? As I said, I'd rather use the entry
construct than just bruteforcing an update using insert
with an existing key. Something a newbie Rustacean like me could not possibly know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您替换整个值时,尤其是当您不知道(或关心)该值是否存在时,
insert()
更为惯用。当您想要对需要可变性的值执行某些操作(例如仅替换结构体的一个字段或调用需要可变引用的方法)时,
get_mut()
更为惯用。如果您知道密钥存在,则可以使用.unwrap()
,否则您可以使用其他Option
实用程序或match
之一。entry(...).and_modify(...)
本身很少是惯用的;当将Entry
的其他方法链接在一起时,例如您想要修改某个值(如果存在),否则添加不同的值时,它会更有用。在使用值为总计的地图时,您可能会看到这种模式:insert()
is a bit more idiomatic when you are replacing an entire value, particularly when you don't know (or care) if the value was present to begin with.get_mut()
is more idiomatic when you want to do something to a value that requires mutability, such as replacing only one field of a struct or invoking a method that requires a mutable reference. If you know the key is present you can use.unwrap()
, otherwise you can use one of the otherOption
utilities ormatch
.entry(...).and_modify(...)
by itself is rarely idiomatic; it's more useful when chaining other methods ofEntry
together, such as where you want to modify a value if it exists, otherwise add a different value. You might see this pattern when working with maps where the values are totals: