Andrew's Digital Garden

Interfaces in Go

Go interfaces are unlike most other languages, and are more akin to a typesafe duck-typing. An interface contains only a list of one or more function signatures but does not implement any of them. This happens implicitly. That is, the type does not have to declare that it implements this or another interface.

Interfaces in Go don't have names that describe attributes (e.g. Boxable), they have names that describe behaviour (e.g. Reader)

type Helloer interface { Hello(string) }

Creating a type (and method) that matches this interface will automatically implement it, for example:

type Greeting string func (g Greeting) Hello(name string) { fmt.Println(g+",", name) }

When a function accepts an interface type as a parameter, we can pass any type to the function that satisfies the interface. The function then can use the passed-in argument in a uniform way without having to care about the concrete type behind the interface.

Interfaces are implemented as two elements, a type (T) and a value (V).

An interface value that holds a nil concrete value is itself non-nil (as it will have a type). If the concrete value inside the interface itself is nil, the method will be called with a nil receiver. If neither exist, the interface is nil - calling a method on this is a runtime error.

[[20210219134407-go-interface-nil]]

[[go]]

Interfaces in Go