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.
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.
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:
