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
}
Starting in Go 1.18 you can use any — alias of interface{} as type of field or variable. It looks better than interface{}.
type Foo struct {
data any
}
Or also you can design the struct as accepting a type parameter. This way it becomes truly generic:
type Foo[T any] struct {
data T
}
Usage:
foo := Foo[string]{data: "hello"}
The main difference is that Foo values without type parameter can be compared using == and != with other Foo values, and yield true or false based on the actual fields. The type is the same! — In case of interface{}/any fields, it will compare the values stored in there. Instances of Foo[T any] instead can NOT be compared with compilation error; because using different type parameters produces different types altogether — Foo[string] is not the same type as Foo[int]. Check it here -> https://go.dev/play/p/zj-kC0VvlUH?v=gotip
All Go types implement the empty interface interface{}.
type Foo struct {
data interface{}
}
The empty interface is covered in A Tour of Go, The Laws of Reflection and the specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With