我可以使用方法或函数作为闭包吗?

Kit*_*tes 4 rust

我在结构上有一些方法想作为参数传递。我很确定传递函数的唯一方法是使用闭包。有没有办法我可以不做 || { self.x() }呢?

She*_*ter 7

您可以绝对使用方法或函数作为闭包。您使用函数或方法的完整路径,包括特征方法:

免费功能:

struct Monster {
    health: u8,
}

fn just_enough_attack(m: Monster) -> u8 {
    m.health + 2
}

fn main() {
    let sully = Some(Monster { health: 42 });
    let health = sully.map(just_enough_attack);
}
Run Code Online (Sandbox Code Playgroud)

一种固有的方法:

struct Monster {
    health: u8,
}

impl Monster {
    fn health(&self) -> u8 { self.health }
}

fn main() {
    let sully = Some(Monster { health: 42 });
    let health = sully.as_ref().map(Monster::health);
}
Run Code Online (Sandbox Code Playgroud)

特征方法:

fn main() {
    let name = Some("hello");
    let owned_name = name.map(ToOwned::to_owned);
}
Run Code Online (Sandbox Code Playgroud)

请注意,参数类型必须完全匹配,这包括按引用或按值。

  • 顺便说一下,特质方法可以通过几种方式指定,例如,str :: to_owned`有效(当范围内的str上只有一个to_owned时),而<str> :: to_owned和<str如ToOwned> :: to_owned`,后者是完全限定的格式。 (2认同)