您可以绝对使用方法或函数作为闭包。您使用函数或方法的完整路径,包括特征方法:
免费功能:
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)
请注意,参数类型必须完全匹配,这包括按引用或按值。
| 归档时间: |
|
| 查看次数: |
958 次 |
| 最近记录: |