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:

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