13

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
}
0

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.