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

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

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

android - How to create dynamically Fragment pager adapter -