1 回答

TA貢獻1829條經驗 獲得超6個贊
如果您想明確表示您實際上并未在函數中使用,則只需添加[T]到GenericCacheWrapperor的末尾即可。[_]T
package main
import (
"encoding/json"
"fmt"
)
type GenericCacheWrapper[T any] struct {
Container T
}
func (c GenericCacheWrapper[T]) MarshalBinary() (data []byte, err error) {
return json.Marshal(c.Container)
}
func (c GenericCacheWrapper[T]) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &c.Container)
}
func main() {
wrapper := GenericCacheWrapper[int]{Container: 4}
data, err := wrapper.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println(data)
}
此規則在語言規范中定義:
泛型類型也可能有與之關聯的方法。在這種情況下,方法接收者必須聲明與泛型類型定義中存在的相同數量的類型參數。
但這背后的原因不是很清楚,也許是為了使編譯器/類型檢查的實現更容易。
相關:Go error: cannot use generic type without instantiation
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報