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
一样,后者是完全限定的形式。