rust - Can a trait be passed as a Fn reference or closure -
in rust, can take in reference fn
documented:
fn call_with_one(some_closure: &fn(i32) -> i32) -> i32 { some_closure(1) } let answer = call_with_one(&|x| x + 2);
however want write trait that, if implemented, runnable can passed expects fn()
. possible?
trait runnable { fn run(&self); } struct myrunnable; impl runnable myrunnable { fn run(&self) {} } struct structthattakesclosure<'life> { closure_field: &'life fn(), } fn main() { // there way change runnable trait automatically match // fn() interface such myrunnable instance can passed directly? structthattakesclosure { closure_field: &|| myrunnable.run() }; }
i have tried implementing 3 extern
calls default functions didn't manage working.
this not possible on stable rust, because exact definition of fn
trait unstable.
on nightly rust can implement fn
traits, concrete types, it's not helpful.
impl<'a> std::ops::fn<()> myrunnable { extern "rust-call" fn call(&self, ():()) { self.run(); } }
Comments
Post a Comment