【发布时间】:2019-04-12 13:31:48
【问题描述】:
我正在尝试简化我的闭包,但是当参数归闭包所有但内部函数调用只需要一个引用时,我在将我的闭包转换为对关联函数的引用时遇到了问题。
#![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 可以在这种情况下使用,但这不是我正在处理的真实情况。
【问题讨论】:
-
如果您能够更改
my_method签名,则可以将其写为fn my_method(prm: impl Borrow<BorrowedStruct>)并接受按值和按引用。 -
注意:静态方法在 Rust 中通常称为associated functions。
-
@rodrigo,您能否分享一下
&BorrowedStruct和impl Borrow<BorrowedStruct>之间的差异的参考 -
当然! official documentation 既完整又令人困惑(至少对我而言)。 TL;DR;问题是
Borrow<T>既适用于T,也适用于&T,甚至适用于Cow<'a,T>。 -
此外,它是一个关联函数这一事实与这里无关——同样的问题也适用于常规函数。