作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图简化我的闭包,但是当参数由闭包拥有但内部函数调用只需要一个引用时,我在将我的闭包转换为对关联函数的引用时遇到了问题。
#![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's answer 中所示,但一般的解决方案是像您所做的那样简单地自己获取引用:
something_taking_a_closure(|owned_value| some_function_or_method(&owned_value))
我其实advocated for this case about two years ago作为人体工程学改造的一部分,但似乎没有其他人对此感兴趣。
在您的特定情况下,您可以从闭包参数中删除类型以使其更简洁:
.for_each(|consumed_struct| MyStruct::my_method(&consumed_struct))
关于rust - 可以将采用引用的函数作为提供自有值的闭包参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55652824/
我有一个 iOS 应用程序项目,有几个私有(private)(拥有)carthage 依赖项,有时我需要调试错误或知道某些方法执行的代码是什么。 我想知道是否有一种简单的方法可以使用运行脚本在 Car
我是一名优秀的程序员,十分优秀!