rust - Can I use a method or a function as a closure? -
i have methods on struct i'd pass around parameters. i'm pretty sure way pass around functions using closures. there way can without doing || { self.x() }
?
you can absolutely use method or function closure. use full path function or method, including trait methods:
a free function:
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); }
an inherent method:
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); }
a trait method:
fn main() { let name = some("hello"); let owned_name = name.map(toowned::to_owned); }
note argument type must match exactly, includes by-reference or by-value.
Comments
Post a Comment