declaring generic type object in go

use*_*195 4 object go

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)

Cer*_*món 5

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.


bla*_*een 5

从 Go 1.18 开始,您可以使用any\xe2\x80\x94 别名作为interface{}字段或变量的类型。看起来比interface{}.

\n
type Foo struct {\n   data any\n}\n
Run Code Online (Sandbox Code Playgroud)\n

或者您也可以将结构设计为接受类型参数。这样它就变得真正通用了:

\n
type Foo[T any] struct {\n   data T\n}\n
Run Code Online (Sandbox Code Playgroud)\n

用法:

\n
foo := Foo[string]{data: "hello"}\n
Run 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]

\n