...

/

Comprehending Go Interfaces

Comprehending Go Interfaces

Understand Go interfaces, how to define them, and their functionalities.

Introduction

Go provides a type called an interface that stores any value that declares a set of methods. The implementing value must have declared this set of methods to implement the interface. The value may also have other methods besides the set declared in the interface type.

If you are new to interfaces, understand that they can be a little confusing. Therefore, we will take it one step at a time.

Defining an interface type

Interfaces are most commonly defined using the type keyword that we discussed in the earlier section on structs. The following defines an interface that returns a string representing the data:

Press + to interact
type Stringer interface {
String() string
}

Note: Stringer is a real type defined in the standard library's fmt package. Types that implement Stringer will have their String() method called when passed to print functions in the fmt package. ...