This lesson gives an introduction to interfaces in Go using an example, also explains how to define a new type that would implement the same interface.

We'll cover the following


An interface type is defined by a set of methods. A value of interface type can hold any value that implements those methods. Interfaces increase the flexibility as well as the scalability of the code. Hence, it can be used to achieve polymorphism in Golang. Interface does not require a particular type, specifying that only some behavior is needed, which is defined by a set of methods.


Here is a refactored version of our earlier example. This time we made the greeting feature more generic by defining a function called Greet which takes a param of interface type Namer. Namer is a new interface we defined which only defines one method: Name(). So Greet() will accept as param any value which has a Name() method defined.

To make our User struct implement the interface, we defined a Name() method. We can now call Greet and pass our pointer to User type.

Get hands-on with 1200+ tech skills courses.