[英]the trait `for<'r> core::ops::FnMut<(&'r &(K, T),)>` is not implemented for the type `P`
I want a sorted vector of (Key, Type), which is sorted only by Key. 我想要一个(Key,Type)的排序向量,它只按Key排序。
I came up with the code below: 我想出了下面的代码:
struct SortedVec<K, T> {
data: Vec<(K, T)>
}
impl<K: Ord, T> SortedVec<K, T> {
fn new() -> SortedVec<K, T> {
SortedVec { data: Vec::new() }
}
fn add(&mut self, k: K, t: T) {
self.data.push((k, t));
self.data.sort_by(|a, b| a.0.cmp(&b.0));
}
fn find<P>(&self, predicate: P) -> Option<&(K, T)> where P: FnMut(&(K, T)) -> bool {
self.data.iter().find(predicate)
}
}
But this doesn't compile with the following errors: 但是这不能编译以下错误:
anon>:16:30: 16:45 error: the trait `for<'r> core::ops::FnMut<(&'r &(K, T),)>` is not implemented for the type `P` [E0277]
anon>:16 self.data.iter().find(predicate)
^~~~~~~~~~~~~~~
<anon>:16:30: 16:45 error: the trait `for<'r> core::ops::FnOnce<(&'r &(K, T),)>` is not implemented for the type `P` [E0277]
<anon>:16 self.data.iter().find(predicate)
^~~~~~~~~~~~~~~
error: aborting due to 2 previous errors
playpen: application terminated with error code 101
I can't find anything wrong with the type 'P'. 我找不到类型'P'的任何问题。
How can I fix it? 我该如何解决?
Let's compare the bound on P
and that required the compiler: 让我们比较P
上的界限和编译器所需的界限:
// P
FnMut( &(K, T)) -> bool
// required
for<'r> FnMut(&'r &(K, T)) -> bool
If you change the where
clause to match the signature asked for by the compiler, it works ( see here ). 如果更改where
子句以匹配编译器要求的签名,则它可以工作( 请参阅此处 )。
I believe the extra reference (and lifetime) are introduced by the use of iter
, and thus linked to the lifetime of the iterator, but don't take my word for it. 我相信额外的引用(和生命周期)是通过使用iter
引入的,因此链接到迭代器的生命周期,但是不要相信我的话。
I would point out, though, that Vec
has a binary_search_by
which is bound to be more efficient than a linear find
: 不过,我会指出, Vec
有一个binary_search_by
,它必然比线性find
更有效:
fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
where F: FnMut(&T) -> Ordering
You may wish to use that instead, since you went to the trouble of sorting it. 您可能希望使用它,因为您遇到了排序它的麻烦。
Well, the compiler already gave you a hint at the fix! 那么,编译器已经给你一个修复提示! You need to change the "where" clause from 您需要更改“where”子句
fn find<P>(&self, predicate: P) -> Option<&(K, T)>
where P: FnMut(&(K, T)) -> bool
to 至
fn find<P>(&self, predicate: P) -> Option<&(K, T)>
where for<'r> P: FnMut(&'r &(K, T)) -> bool
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.