dtddjq9637 2018-10-15 22:18
浏览 58

Golang中的功能接口

Consider such function that accepts function as argument:

func f(arg func(I)){}

where I is interface.

Is there any way to pass into above function an argument of signature func(*T) where T implements I interface.

Now when I pass it, I have an error:

cannot use (type func(*T)) as type func(I) in argument

Here is playground: https://play.golang.org/p/7vilY4zkEzf

Use case is the following:

I write package that has f(a func(I), b I) function. Then user will import it as library.

As a next step, user will define a custom type T that implements I interface and a custom function with signature func(*T) . Then user will call library f function:

f(customFunction, customObject)

In turn, package will receive it and create a goroutine:

go  customFunction(customObject)

The reason why goroutines are created "inside" package is that goroutine orchestration should be hold "under the hood".

  • 写回答

1条回答 默认 最新

  • dsa5233 2018-10-15 22:34
    关注

    No, the types need to be exact. Your example is especially broken because I isn't definitely convertible to *T, but it also wouldn't work the other way. If you're sure that the type of the I being passed to your function is *T, you could create wrapper function and pass that instead.

    func wrapper(i I) {
      t := i.(*T)
      myRealFunc(t)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用