我有以下通用介面
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
uj5u.com熱心網友回復:
任何應該采用Worker介面的泛型變體的函式本身必須是泛型函式。
func TakesAnyWorker[input any, output any](w Worker[input, output]) { ... }
該型別Worker[any, any]不是泛型型別,并且僅與實作的值兼容,Process(any) any因為這是您的介面定義所要求的。
在您的示例中,該函式是一種方法,在 Go 1.19 中不能采用型別引數。如果一個單一的WorkManager總是采用Worker相同型別的 s,那么您可以WorkManager像這樣創建一個全等的泛型型別:
type WorkManager[input any, output any] struct { ... }
func (m *WorkManager[input, output]) RegisterWorker(f Worker[input, output]) uuid.UUID
如果你的單WorkManager需要使用Worker不同型別的 s,那么我擔心你遇到的問題比泛型可以解決的更大,你將被迫使用常規介面和reflect.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510479.html
標籤:去仿制药
