是否可以将对象方法作为参数传递给函数并将其绑定到对象? [英] Is it possible to pass an object method as argument to a function and bind it to the object?
问题描述
是否可以绑定到对象方法?例如,我有一个向量和许多函数,如果向量中存在某些项目,它们会执行某些操作.我会按如下方式实现它:
Is it possible to make a bind to object method? For example, I have a vector and a lot of functions which do something if some item exists in the vector. I would implement it as follows:
fn perform_if_exists(item: u8, vector: &Vec<u8>, func: fn(usize)) {
let idx = vector.iter().position(|i| *i == item );
match idx {
Some(i) => func(i),
None => {},
}
}
fn main() {
let v: Vec<u8> = vec![1, 2, 3];
perform_if_exists(1, &v, Vec<_>::remove);
}
但它给出了很多错误.我认为它们是合理的,但这是因为我不明白如何将 vector 的方法作为函数的参数.
but it gives a lot of errors. I think they are reasonable but it's because I don't understand how to put vector's method as argument to a function.
推荐答案
有没有可能
当然是.您必须先修复多个级联错误:
Sure it is. You have to fix the multiple cascading errors first:
- 无效语法:
Vec<_>::remove
无效. - 不兼容的参数类型:
Vec::remove
修改了 aVec
,所以你必须传入一个Vec
不知何故. - 可变性:
Vec::remove
修改一个Vec
,所以你必须声明允许该函数这样做.立> Vec::remove
返回移除的值,所以你必须允许函数返回一个值,即使它被丢弃.
- Invalid syntax:
Vec<_>::remove
isn't valid. - Incompatible argument types:
Vec::remove
modifies aVec
, so you have to pass in aVec
somehow. - Mutability:
Vec::remove
modifies aVec
, so you have to declare that the function is allowed to do so. Vec::remove
returns the removed value, so you have to allow the function to return a value, even if it's thrown away.
fn perform_if_exists<F, R>(item: u8, vector: &mut Vec<u8>, func: F)
where F: Fn(&mut Vec<u8>, usize) -> R
{
let idx = vector.iter().position(|i| *i == item );
if let Some(i) = idx {
func(vector, i);
}
}
fn main() {
let mut v = vec![1, 2, 3];
perform_if_exists(1, &mut v, Vec::remove);
println!("{:?}", v);
}
我改用了泛型,因为这通常是您接受闭包的方式.函数指针很好,但限制更多.
I switched to a generic as that's generally how you will accept closures. A function pointer is fine but more restrictive.
这篇关于是否可以将对象方法作为参数传递给函数并将其绑定到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!