创建一个通用函数,可以接受任何函数及其相关参数,以便稍后执行。

huangapple go评论94阅读模式
英文:

create generic function which can accept any function with its related args for later execution

问题

是否可以创建一个通用函数,该函数可以接受任何其他函数及其相关参数,并在以后用于执行传递的函数。我有一个需求,计划首先收集所有这些调用,并维护这些"作业"的一些元数据,然后通过Go协程稍后执行它们。

// 一种作业函数
func someCoolJob(arg1 type1, arg2 type2) type3 {
    // 进行处理
    return "type3的值"
}

现在是否可以创建一个通用函数,可以接受任何签名的函数。以前我在Python中做过类似的实现,Go中是否有类似的方法?

func processor(someFunc, relatedArgs){
    // 在这里保存一些执行信息/跟踪状态

    // 稍后可以在我的代码中执行以下操作
    go someFunc(relatedArgs)
}

在Go中是否有更好的组织方式?其他实现方式?

英文:

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 ?

答案1

得分: 2

通过使用闭包将参数传递。

processor更改为接受没有参数的函数。

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

使用闭包传递函数和参数:

processor(func() { someCoolJob(arg1, arg2) })
英文:

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) })

huangapple
  • 本文由 发表于 2022年2月20日 15:39:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71192265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定