Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 我可以使用方法或函数作为闭包吗?_Rust - Fatal编程技术网

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

Rust 我可以使用方法或函数作为闭包吗?,rust,Rust,我有一些关于结构的方法,我想作为参数传递。我很确定传递函数的唯一方法是使用闭包。有没有一种方法可以让我不用做这些 |{self.x()}?您完全可以使用方法或函数作为闭包。使用函数或方法的完整路径,包括trait方法: 自由函数: struct Monster { health: u8, } fn just_enough_attack(m: Monster) -> u8 { m.health + 2 } fn main() { let sully = Some(

我有一些关于结构的方法,我想作为参数传递。我很确定传递函数的唯一方法是使用闭包。有没有一种方法可以让我不用做这些
|{self.x()}

您完全可以使用方法或函数作为闭包。使用函数或方法的完整路径,包括trait方法:

自由函数:

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);
}
固有方法:

特质方法:

fn main() {
    let name = Some("hello");
    let owned_name = name.map(ToOwned::to_owned);
}

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

您完全可以使用方法或函数作为闭包。使用函数或方法的完整路径,包括trait方法:

自由函数:

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);
}
固有方法:

特质方法:

fn main() {
    let name = Some("hello");
    let owned_name = name.map(ToOwned::to_owned);
}

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

顺便说一句,trait方法可以通过几种方式指定,例如,
str::to_owned
有效(当
str
范围内只有一个
to_owned
时,
::to_owned
::to_owned
,后者是完全限定的形式。顺便说一句,trait方法可以用几种方式指定,例如
str::to_owned
有效(当范围
str
上只有一个
to_owned
时),就像
::to_owned
::to_owned
一样,后者是完全限定的形式。