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.