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

我有以下通用接口


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


ABOUTYOU
浏览 77回答 1
1回答

九州编程

任何应该采用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.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go