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

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

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

问题

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

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

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

  1. func processor(someFunc, relatedArgs){
  2. // 在这里保存一些执行信息/跟踪状态
  3. // 稍后可以在我的代码中执行以下操作
  4. go someFunc(relatedArgs)
  5. }

在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.

  1. // some kind of job function
  2. func someCoolJob(arg1 type1, arg2 type2) type3 {
  3. // do processing
  4. return "value of type3"
  5. }

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 ?

  1. func processor(someFunc, relatedArgs){
  2. // I will save some execution info/ tracking state for someFunc here
  3. // later I can do something like below in my code
  4. go someFunc(relatedArgs)
  5. }

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

答案1

得分: 2

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

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

  1. func processor(fn func()){
  2. go fn()
  3. }

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

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

Pass the arguments through using a closure.

Change processor to take a function with with no arguments.

  1. func processor(fn func()){
  2. go fn()
  3. }

Pass the function and arguments using a closure:

  1. 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:

确定