Is there a generic type Object in golang similar to other languages that can be assigned any kind of payload?
type Foo struct {
data object
}
Run Code Online (Sandbox Code Playgroud)
All Go types implement the empty interface interface{}.
type Foo struct {
data interface{}
}
Run Code Online (Sandbox Code Playgroud)
The empty interface is covered in A Tour of Go, The Laws of Reflection and the specification.
从 Go 1.18 开始,您可以使用any\xe2\x80\x94 别名作为interface{}字段或变量的类型。看起来比interface{}.
type Foo struct {\n data any\n}\nRun Code Online (Sandbox Code Playgroud)\n或者您也可以将结构设计为接受类型参数。这样它就变得真正通用了:
\ntype Foo[T any] struct {\n data T\n}\nRun Code Online (Sandbox Code Playgroud)\n用法:
\nfoo := Foo[string]{data: "hello"}\nRun Code Online (Sandbox Code Playgroud)\n主要区别在于,没有类型参数的值可以使用和与其他值Foo进行比较,并根据实际字段产生 true 或 false。类型是一样的!\xe2\x80\x94 如果是/字段,它将比较存储在其中的值。相反的实例不能与编译错误进行比较;因为使用不同的类型参数会产生不同的类型 \xe2\x80\x94与 不同。在这里检查 -> https://go.dev/play/p/zj-kC0VvlUH?v=gotip==!=Foointerface{}anyFoo[T any]Foo[string]Foo[int]