我尝试使用print语句重新实现Vec::retain()
,以便我可以弄清楚它是如何工作的,但我仍然坚持使用此扩展类型注释where F: FnMut(&T) -> bool
。我明白为什么会这样,但我无法弄清楚如何在特征声明中注释它以便它停止抛出错误(并让我修复代码中的其他错误):
trait TestVec {
fn retain_with_prints<F>(&mut self, mut f: F);
}
impl<T> TestVec for Vec<T> {
fn retain_with_prints<F>(&mut self, mut f: F)
where F: FnMut(&T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
println!("on position: {}", &i);
if !f(&v[i]) {
del += 1;
println!("incremented del to: {}", del);
} else if del > 0 {
println!("swapping {} for {}", v[i - del], v[i]);
v.swap(i - del, i);
}
}
}
if del > 0 {
println!("removing last {} elements of vector", del);
self.truncate(len - del);
}
}
}
fn main() {
let v = vec![0,1,2,3,4,5];
v.retain_with_prints(|item| { item % 2 == 0 });
}
错误:
error: the requirement `for<'r> F: std::ops::FnMut<(&'r T,)>` appears on the impl method but not on the corresponding trait method [E0276]
where
子句添加到特征:error: type name `T` is undefined or not in scope [E0412]
如果我尝试指定trait<T>
,编译器似乎也不喜欢它,我似乎无法在搜索结果中找到正确的东西。
如何指定?
答案 0 :(得分:3)
您需要参数化特征:
trait TestVec<T> {
fn retain_with_prints<F>(&mut self, mut f: F)
where F: FnMut(&T) -> bool;
}
并在实施时链接类型。
impl<T> TestVec<T> for Vec<T>
除此之外,您需要要求您的T实现Display
并使您的变量可变:
impl<T> TestVec<T> for Vec<T>
where T: std::fmt::Display
{
let mut v = vec![0,1,2,3,4,5];