我有以下通用接口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
.
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报
0/150
提交
取消