在下面的代码中,我定义了一个类型Bird
,然后定义了一个类型Birdwatcher
,它的HashSet
是birds_seen
。Birdwatcher
s有一个方法.see(bird)
,它将bird
插入到它们的HashSet中。(在上下文中,这个方法有一些其他的逻辑,所以我们不能直接调用hashset的.insert()
方法。
在main()
函数中,我示例化了一只鸟和两个观鸟者。如果我尝试让两个birdwatchers .see()
都是同一只鸟,代码将无法编译:
use std::collections::HashSet;
fn main() {
let falcon = Bird { name: "falcon".to_string(), speed: 25 };
let mut alice = Birdwatcher { name: "Alice".to_string(), birds_seen: HashSet::new() };
let mut bobby = Birdwatcher { name: "Bobby".to_string(), birds_seen: HashSet::new() };
alice.see(falcon);
// use of moved value: `falcon`
// bobby.see(falcon);
}
#[derive(Hash, Eq, PartialEq)]
struct Bird {
name: String,
speed: isize,
}
struct Birdwatcher {
name: String,
birds_seen: HashSet<Bird>,
}
impl Birdwatcher {
fn see(&mut self, bird: Bird) {
// Additional logic goes here
self.birds_seen.insert(bird);
}
}
我想我可以通过改变.see()
方法来借用bird来解决这个问题,如下所示,但由于类型不匹配,这无法编译:
impl Birdwatcher {
fn see(&mut self, bird: &Bird) {
// mismatched types: expected `Bird`, found `&Bird`
self.birds_seen.insert(bird);
}
}
如何编写.see()
方法,以允许多个观鸟者看到同一只鸟?
1条答案
按热度按时间gwbalxhn1#
我们不需要“使用”鸟来将它们存储在散列集中;我们可以只计算它们的散列(一次)并将其添加到集合中。
一个
HashSet
不是一个 * 散列 * 的集合;它是一个使用哈希的集合。它仍然包含、拥有插入的值,就像Vec
或Rust中的任何其他常规集合类型一样。这是必要的,因为散列可能会冲突-它们没有足够的位来实际保证不冲突-在这种情况下,集合将不得不退回到将值本身与
Eq
进行比较。此外,HashSet
允许对项进行迭代或删除项,因此它必须拥有这些项才能生成它们。如果你想要一个只存储哈希值的集合,你需要创建一个哈希值的集合,而不是那些被哈希产生的值的集合。