Sobes.tech
Senior

What is an interface in Go? What is under the hood? How much does an empty interface weigh?

sobes.tech AI

Answer from AI

In Go, an interface is a set of methods that a type must implement to be considered as implementing that interface. An interface describes behavior, not data structure.

Under the hood, an interface in Go is represented by two pointers: one points to a method table (type descriptor), and the other points to the data of the specific value. This allows dynamic method calls on types.

The empty interface interface{} contains no methods and can hold a value of any type. Its size is usually two pointers (16 bytes on 64-bit systems), as it stores a pointer to the type and a pointer to the data.

Example:

var i interface{} = 42
fmt.Printf("%T %v", i, i) // int 42

Here, i can hold any value because the empty interface imposes no restrictions.

What is an interface in Go? What is under the hood… - sobes.tech