Chapter 10

Defining Method Signatures Using Interfaces

IN THIS CHAPTER

Bullet Defining and implementing an interface in Go

Bullet Seeing how you may use an interface

Earlier in this book, I explain structs and how you can define methods in them. Another important topic in Go that is often not easy to grasp is that of interfaces. An interface defines the behavior of an object, specifying the methods that it needs to implement.

Interfaces serve two important purposes in Go:

  • They make your code more versatile.
  • They force you to adopt code encapsulation (the practice of hiding the implementation of your methods).

In this chapter, I explain what an interface is in Go and show you how to use it in your program. To make this topic less abstract, I illustrate interfaces with a few concrete examples.

Working with Interfaces in Go

An interface is an abstract type. It describes all the methods that a type can implement. But it only provides the method signatures, leaving the implementation entirely to the implementing type. So, you can say that interface defines, and doesn’t declare, the behavior of an object of a specific type.

You may still feel a bit fuzzy on interfaces, but stick with me, and I’ll show you some concrete examples.

Defining an interface

Let’s first start by defining an interface ...

Get Go Programming Language For Dummies now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.