Syntax 为什么特征绑定出现在where子句中而不出现在函数签名中?
我正在阅读,但在源代码中找不到类型参数Syntax 为什么特征绑定出现在where子句中而不出现在函数签名中?,syntax,rust,Syntax,Rust,我正在阅读,但在源代码中找不到类型参数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) } pub-fn-ge
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)
}
pub-fn-get(&self,k:&Q)->选项
其中K:借用,
Q:Hash+Eq
{
self.search(k.map)(| bucket | bucket.into_refs().1)
}
K
是HashMap
的一个类型参数,介绍如下:
我认为
get
方法体中的search
方法使用K:Borrow
特征边界,因此get
方法需要相同的特征边界。关于对get方法参数中的键值使用
&str
或&String
,仅使用
&Q
类型就足够了
impl<K, V, S> HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
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)