我正在阅读HashMap的get功能,但我K在源代码中找不到类型参数.
为什么K特征绑定存在于where子句中,而不存在于函数签名中?
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>,
Q: Hash + Eq
{
self.search(k).map(|bucket| bucket.into_refs().1)
}
Run Code Online (Sandbox Code Playgroud)
K是一个类型参数,HashMap<K, V, S>它是在适用impl块的开头引入的:
impl<K, V, S> HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
Run Code Online (Sandbox Code Playgroud)
它适用于整个块,包括get,它增加了一个额外的约束,K: Borrow<Q>.
这种指定gets 类型的方式k可能有点尴尬,但它使我们能够执行以下操作:
let mut map: HashMap<String, usize> = HashMap::new();
map.insert("herp".to_string(), 1);
map.insert("derp".to_string(), 2);
assert_eq!(map.get("herp"), Some(&1)); // we can search by &'static str (not only by a String)
Run Code Online (Sandbox Code Playgroud)