我试图简化闭包,但是当参数由闭包拥有但内部函数调用仅需要引用时,将我的闭包转换为对关联函数的引用时遇到问题。
#![deny(clippy::pedantic)]
fn main() {
let borrowed_structs = vec![BorrowedStruct, BorrowedStruct];
//Selected into_iter specifically to reproduce the minimal scenario that closure gets value instead of reference
borrowed_structs
.into_iter()
.for_each(|consumed_struct: BorrowedStruct| MyStruct::my_method(&consumed_struct));
// I want to write it with static method reference like following line:
// for_each(MyStruct::my_method);
}
struct MyStruct;
struct BorrowedStruct;
impl MyStruct {
fn my_method(prm: &BorrowedStruct) {
prm.say_hello();
}
}
impl BorrowedStruct {
fn say_hello(&self) {
println!("hello");
}
}
是否可以简化此代码:
into_iter().for_each(|consumed_struct: BorrowedStruct| MyStruct::my_method(&consumed_struct));
要以下内容:
into_iter().for_each(MyStruct::my_method)
请注意,into_iter
这里仅重现了我在闭合中拥有值的情况。我知道iter
可以在这种情况下使用,但这不是我正在研究的实际情况。
您的一般问题的答案是否定的。在将函数作为闭包参数传递时,类型必须完全匹配。
如罗德里格(Rodrigo)的答案所示,有一种一次性的解决方法,但是一般的解决方案是像您所做的那样简单地自己获取参考:
something_taking_a_closure(|owned_value| some_function_or_method(&owned_value))
实际上,大约在两年前,我作为人机工程学改造的一部分倡导了这种情况,但似乎没有人对此感兴趣。
在您的特定情况下,可以从闭包参数中删除该类型以使其更加简洁:
.for_each(|consumed_struct| MyStruct::my_method(&consumed_struct))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句