为了账号安全,请及时绑定邮箱和手机立即绑定

如何使函数接受实现通用接口的结构?

如何使函数接受实现通用接口的结构?

Go
ABOUTYOU 2023-02-14 15:21:56
我有以下通用接口type Worker[input any, output any] interface {    Process(input) output}我正在尝试使用以下方法实现接口type IntWorker[i int, o int] struct{}func (w *IntWorker[i, o]) Process(input i) o {    fmt.Println("running i")    return 1}当我尝试使用它时,出现以下错误mgr := internal.NewWorkManager()iwkr := &IntWorker[int, int]{}mgr.RegisterWorker(iwkr)cannot use iwkr (variable of type *IntWorker[int, int]) as internal.Worker[any, any] value in argument to : *IntWorker[int, int] does not implement internal.Worker[any, any] (wrong type for method Process)        have Process(input int) int        want Process(any) any注意最后一段,它说 want anybut have int。我不确定如何解决这个问题,因为我的印象是你可以将任何东西传递给any变量被传递给这个函数:func (m *WorkManager) RegisterWorker(f Worker[any, any]) uuid.UUID
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

任何应该采用Worker接口的通用变体的函数本身必须是通用函数。

func TakesAnyWorker[input any, output any](w Worker[input, output]) { ... }

该类型Worker[any, any]不是通用类型,并且仅与实现的值兼容,Process(any) any因为这是您的接口定义所指示的。

在您的示例中,该函数是一种方法,在 Go 1.19 中不能采用类型参数。如果 singleWorkManager总是采用Worker相同类型的 s ,那么您可以WorkManager像这样使 the 成为一个一致的泛型类型:

type WorkManager[input any, output any] struct { ... }
func (m *WorkManager[input, output]) RegisterWorker(f Worker[input, output]) uuid.UUID

如果您的单身人士WorkManager需要采用Worker不同类型的 s,那么恐怕您遇到的问题比泛型可以解决的问题更大,您将被迫使用常规接口和reflect.


查看完整回答
反对 回复 2023-02-14
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号