Rust generic higher order function which take the struct method as argument and invokes it

Hi I am new to Rust and trying to write a generic higher-order function which will take
the struct method and some input as an argument, invoke the given struct method with given input and return the result.

The struct I have looks like below:

struct MyStruct {
   typeA: MyTypeA,
   typeB: MyTypeB,
}

impl struct {

  async fn method1(&self, argA: ArgTypeA, argB: argTypeB) -> Result<O1, Error> {
    //impl goes here.
  }

  async fn method2(&mut self, argA: ArgTypeA, argB: argTypeB, argC: argTypeC) -> Result<O2, Error> {
    //impl goes here.
  }

  async fn method3(&mut self, argA: ArgTypeA, argB: argTypeB) -> Result<O3, Error> {
    //impl goes here.
  }
}

The struct implements trait and which has some boilerplate code that is repeated across all the 3 method of the struct.

impl MyTrait for MyStruct {

   fn methodA(&self, argA: ArgTypeA, argB: argTypeB) -> Result<O1, Error> {
      // duplicated logic goes here
      let output = tokio::runtime::Builder::new_current_thread().build().unwrap().block_on({async {self.method1(argA, argB)}});
      // duplicated logic goes here
   }
   
  fn methodB(&self, argA: ArgTypeA, argB: argTypeB) -> Result<O1, Error> {
      // duplicated logic goes here
      let output = tokio::runtime::Builder::new_current_thread().build().unwrap().block_on({async {self.method2(argA, argB)}});
      // duplicated logic goes here
   }

  fn methodC(&self, argA: ArgTypeA, argB: argTypeB) -> Result<O1, Error> {
      // duplicated logic goes here
      let output = tokio::runtime::Builder::new_current_thread().build().unwrap().block_on({async {self.method3(argA, argB)}});
      // duplicated logic goes here
   }
}

I am trying to write a higher order generic function that abstracts the duplicated logic but not sure how to write and call it, I have tried below but does not seems to be working

fn my_generic_method<F, I, O>(func: F, input: I) -> O
where 
 F: F(I) -> O {
   
}

any help/pointer is highly appreciated.

What you write can never work. There are so many things which are not possible to do it's not even funny.

  1. It's not possible to call struct method from the generic function. They can only use traits.
  2. You are not writing functions, you are using async function. They can not be in traits.
  3. You generic function would have to be ready to accept pointer to async function, but then it wouldn't work because each async function implements its own type thus they can not be used in generic.

You would have to look on async-trait to see how you can implement bunch of workarounds.

Yes, higher-order function are PITA in Rust.

2 Likes