gpt4 book ai didi

rust - 可以将采用引用的函数作为提供自有值的闭包参数传​​递吗?

转载 作者:行者123 更新时间:2023-11-29 08:15:32 25 4
gpt4 key购买 nike

我试图简化我的闭包,但是当参数由闭包拥有但内部函数调用只需要一个引用时,我在将我的闭包转换为对关联函数的引用时遇到了问题。

#![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");
}
}

Playground

是否可以简化这段代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com