[英]How do I specify “where” annotations in a trait in Rust?
I'm trying to re-implement Vec::retain()
with print statements so that I can figure out how it works, but I'm stuck on this extended type annotation where F: FnMut(&T) -> bool
. 我正在尝试用print语句重新实现
Vec::retain()
,以便我可以弄清楚它是如何工作的,但我仍然坚持这个扩展类型的注释where F: FnMut(&T) -> bool
。 I understand why it's there, but I can't figure out how to annotate it in the trait declaration so it stops throwing errors (and lets me fix the other ones in the code): 我理解为什么它存在,但我无法弄清楚如何在特征声明中注释它,所以它停止抛出错误(并让我修复代码中的其他):
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 });
}
Errors: 错误:
error: the requirement `for<'r> F: std::ops::FnMut<(&'r T,)>` appears on the impl method but not on the corresponding trait method [E0276]
error: the requirement `for<'r> F: std::ops::FnMut<(&'r T,)>` appears on the impl method but not on the corresponding trait method [E0276]
: 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
clause to trait: error: type name `T` is undefined or not in scope [E0412]
where
子句添加到trait: error: type name `T` is undefined or not in scope [E0412]
The compiler doesn't seem to like it if I try to specify trait<T>
either, and I can't seem to get the right thing to come up in search results. 如果我尝试指定
trait<T>
,编译器似乎不喜欢它,我似乎无法在搜索结果中找到正确的东西。
How do I specify this? 我该如何指定?
You need to parameterize the trait: 您需要参数化特征:
trait TestVec<T> {
fn retain_with_prints<F>(&mut self, mut f: F)
where F: FnMut(&T) -> bool;
}
And also link the types at implementation time. 并在实施时链接类型。
impl<T> TestVec<T> for Vec<T>
Beyond that, you will need to require that your T implements Display
and make your variable mutable: 除此之外,您需要要求您的T实现
Display
并使您的变量可变:
impl<T> TestVec<T> for Vec<T>
where T: std::fmt::Display
{
let mut v = vec![0,1,2,3,4,5];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.