Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring generic type object in go

Tags:

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
}
like image 424
user2727195 Avatar asked Mar 08 '17 20:03

user2727195


2 Answers

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

like image 185
Marco Järvinen Avatar answered Oct 16 '22 13:10

Marco Järvinen


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.

like image 23
Bayta Darell Avatar answered Oct 16 '22 13:10

Bayta Darell