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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -