Lesson 15Adding Interfaces

In the previous lessons, we've covered a number of different types that Go supports. Go supports another type as well: interfaces. In its basic form, an interface in Go is a named collection of method signatures without any implementation.

CREATING AN INTERFACE

If you have worked with object-oriented languages before, then you might already be familiar with the concept of an interface. In Go we can define an interface type using the type and interface keywords:

type Name interface {
    // methods
}

After creating an interface, we can create variables based on that interface. The values stored in those variables implement the methods of the interface.

In other programming languages, such as Java, we normally use the implements keyword to implement an interface. In Go programming, we use the simple convention that the value of an interface type can only hold values of a type that implements the methods of the interface. To understand the concept of interfaces, consider the code in Listing 15.1.

Get Job Ready Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.