【问题标题】:Rust HashMap find_or_insertRust HashMap find_or_insert
【发布时间】:2014-01-16 20:47:26
【问题描述】:

为什么 HashMap.find_or_insert(k,v) 返回一个 &mut 类型,它如何让它返回一个type

我刚开始在课程中使用 Rust,我正在使用 HashMap<int, int> 并希望获得 int 回复。

let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", m.find_or_insert(1,2));

给我一​​个错误,说它failed to find an implementation of trait std::fnt::Signed for &amp;mut int


编辑1:

我在 Windows 8.1 上使用 Rust 0.9,使用 msys。

到目前为止我的代码

use std::hashmap::HashMap;

fn main() {
    let mut m: HashMap<int, int> = HashMap::new();
    println!("{:d}", *m.find_or_insert(1,2))
}

我再次尝试了这段代码,它正确返回2

【问题讨论】:

  • find_or_insert 在 rust 中不再是 HashMap 的方法了。

标签: hashmap rust


【解决方案1】:

为什么find_or_insert 返回一个引用?复制并不总是可行/有效的。

在整数的情况下如何使用该引用?使用 * 取消引用它:

let mut m: HashMap<int, int> = HashMap::new();
println!("{:d}", *m.find_or_insert(1,2));

【讨论】:

  • 您对“为什么”的解释是有道理的,但是当我使用 * 取消引用时,我会在运行时得到 Error: Please provide a number as argument。你知道为什么我没有得到一个 int 吗?
  • @zephyrthenoble:不,我不……你在使用 Rust 0.9 吗?这正是你的代码吗?
  • 我在 Windows 8.1 上使用 Rust 0.9。使用您的代码,我的代码无法编译,因为您没有 。我将编辑我的问题以显示我的确切代码。
  • 2019 find_or_insert 不再存在于搜索中的人。
  • 尾随 @wegry 的评论,在 2019-2020 年,我们可以将其写为 m.entry(1).or_insert(2),因为 find_or_insert 已被弃用。
猜你喜欢
  • 2021-09-27
  • 2021-07-05
  • 2018-11-11
  • 1970-01-01
  • 2017-09-10
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多