Topic Overview and Goals

Welcome to our deep dive into one of the powerful facets of Go programming - interfaces. Think of these as a job description that defines a role's required skills, just as interfaces specify the functions that our Go types need to implement. By the end of this lesson, you will be able to confidently create effective interfaces in Go.

Understanding What Interfaces Are

An interface, in computing, is a communication point between objects; it defines behaviors that an object can implement. Consider a soccer player who must kick a ball, sprint, and follow game rules — these behaviors are akin to methods in an interface.

Internally, an interface in Go is represented by a tuple (type, value), comprising the concrete type of the value it holds and the value itself. This design enables Go's runtime to perform dynamic type checking and allows interfaces to be versatile. When a value is assigned to an interface, Go stores this tuple, facilitating type assertions and interface conversions by preserving the concrete type's information.

One important thing to note is that an interface in Go retains its type even when holding a nil value; thus, it's only truly nil if both the type and value are nil. When not checked properly, this can lead to subtle bugs.

Declaring Interfaces in Go

To declare interfaces in Go, we use the type keyword, followed by the interface's name, the interface keyword, and a set of methods enclosed within {} brackets. Take a look at the example below:

type Player interface {
    Play()
    Score() int
}

Here, we've created a Player interface with two methods: Play and Score. Any type that implements this interface must define these methods.

How Interfaces Interact with Go Types

А type implements an interface by implementing its methods. In Go, there is no explicit declaration that a type implements an interface. To demonstrate this, let's create a struct, Footballer, that implements the Player interface:

type Footballer struct {
    Name  string
    Goals int
}

// Implements the Play method of the Player interface
func (f Footballer) Play() {
    fmt.Println(f.Name, "is playing football!")
}

// Implements the Score method of the Player interface
func (f Footballer) Score() int {
    return f.Goals
}

By defining the Play and Score methods for Footballer, it now implements the Player interface.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal