Working with Go Interfaces

What is a Golang interface?

So, an interface in Go is an abstract type defined using a set of method signatures. The interface defines the behavior for similar types of objects.

Behavior is a key term that we will discuss shortly.

Let’s take a look at an example to understand this better.

A great real-world example of interfaces is a power socket. Imagine that we need to connect different devices to the power socket.

Let’s try to implement this. Here are the device types we will be using.

type mobile struct {
    brand string

type laptop struct {
    cpu string

type toaster struct {
    amount int

type kettle struct {
    quantity string

type socket struct{}

Now, let’s define a Draw method on a type; let’s say mobile. Here we will simply print the properties of the type.

func (m mobile) Draw(power int) {
    fmt.Printf("%T -> brand: %s, power: %d", m, m.brand, power)