我是 Go 的新手,正在为 JSON 封送处理实现数据结构。我想总结一些类型,因为它们具有相同的字段但可能的枚举值不同。因此,我创建了一个具有通用类型约束的结构
json.Unmarshaler
以确保它可以被解组。
我创建了一个最小的例子来说明我的问题:
package main
import "encoding/json"
type MyEnum int
const (
One MyEnum = iota
Two
)
func (e *MyEnum) UnmarshalJSON(b []byte) error {
//...
*e = One
return nil
}
type MyStruct[T json.Unmarshaler] struct {
Value T `json:"value"`
}
type Using struct {
Number int `json:"number"`
Sub MyStruct[MyEnum] `json:"sub"` // Compiler: MyEnum does not satisfy json.Unmarshaler (method UnmarshalJSON has pointer receiver)
}
func main() {
sub = MyStruct[MyEnum]{One} // Compiler: MyEnum does not satisfy json.Unmarshaler (method UnmarshalJSON has pointer receiver)
instance = Using{5, sub}
}
在这里,我想使用
MyStruct
结构中的 Using
和 MyEnum
类型作为结构的 Sub
字段。我在代码中添加了相关的编译器警告。我对它们的理解是,枚举的UnmarshalJSON
函数中的指针是问题所在,但需要指针来实现接口并实际将信息存储在枚举中。