Home > Back-end >  create generic function which can accept any function with its related args for later execution
create generic function which can accept any function with its related args for later execution

Time:02-21

Is it possible to create a generic function which can accept any other function with its related arguments which can be used later to execute the passed function. I have a requirement where I am planning to first collect all these calls and maintain some metadata of these "jobs" and then execute them later via go routines.

// some kind of job function 
func someCoolJob(arg1 type1, arg2 type2) type3 {
    // do processing
    return "value of type3"
}

Now is it possible to create a generic function which can take any function with any signature. Previously I have done similar implementation in python, is there some way in go ?

func processor(someFunc, relatedArgs){
    // I will save some execution info/ tracking state for someFunc here

    // later I can do something like below in my code
    go someFunc(relatedArgs)
}

Is there some better way to organise this in go ? Some other way of implementation ?

CodePudding user response:

Pass the arguments through using a closure.

Change processor to take a function with with no arguments.

func processor(fn func()){
    go fn()
}

Pass the function and arguments using a closure:

processor(func() { someCoolJob(arg1, arg2) })
  • Related