What is an Interface?

This lesson gives a brief introduction to interfaces and explains how Go, having no concepts of classes and inheritance, implements the OO behavior.

Introduction to interface

Go is not a classic OO language. It doesn’t recognize the concept of classes and inheritance. However, it does contain the very flexible concept of interfaces, with which a lot of aspects of object-orientation can be made available. Interfaces in Go provide a way to specify the behavior of an object.

An interface defines a set of methods (the method set), but these methods do not contain code: they are not implemented (they are abstract). Also, an interface cannot contain variables. An interface is declared in the format:

type Namer interface {
    Method1(param_list) return_type
    Method2(param_list) return_type
    ...
}

Namer is an interface type. The name of an interface is formed by the method name plus the [er] suffix, such as Printer, Reader, Writer, Logger, Converter, and so on, thereby giving an active noun as a name. A less-used alternative (when …er is not so appropriate) is to end it with able, like in Recoverable or to start it with an I (more like in .NET or Java). Interfaces in Go are short; they usually have one two three methods (except for the empty interface, which has 0 methods).

Unlike in most OO languages, in Go, interfaces can have values that are a variable of the interface type or an interface value:

var ai Namer

ai is a multiword data structure with an uninitialized value of nil. Although not entirely the same thing, ai is, in essence, a pointer. So, pointers to interface values are illegal; they would be wholly useless and give rise to errors in code.

Get hands-on with 1400+ tech skills courses.