Interfaces in Golang

Interfaces represent an abstraction of other types of behavior. Interfaces allow you to define functions that are not tied to a specific implementation. That is, interfaces define some functionality but do not implement it.

The interface keyword is used to define an interface:

type interface_name interface{

 function_definitions
 }

For example, the simplest interface definition:

type person interface{
    talk()
}

This interface is called a person. Let's say this interface represents a person. It defines a function talk() that takes no parameters and returns nothing.

It is important to understand that an interface is an abstraction, and not a concrete type like int, string, or structures. For example, we cannot directly create an interface object:

var p person = person{}

An interface represents a kind of contract that the data type must conform to. For a data type to correspond to an interface, the type must implement all the functions of that interface as methods. For example, let's define two structures:

package main

import "fmt"

// Interface "Person"
type Person interface {
    walk()
}

// Structure "Human"
type Human struct{}

func (h Human) walk() {
    fmt.Println("The person is walking")
}

// Structure "Animal"
type Animal struct{}

func (a Animal) walk() {
    fmt.Println("The animal is walking")
}

func main() {
    var john Person = Human{}
    var tiger Person = Animal{}

    john.walk()
    tiger.walk()
}

If we run this will get:

The person is walking
The animal is walking

In this example, we define two structures: Human and Animal, representing a person and an animal, respectively. Each structure includes a method named walk() intended to simulate the movement of the entity. The walk method aligns with the Movement interface's walk function in both parameter type and return type. This alignment between the methods of structures and functions in an interface results in the implicit implementation of this interface.

In Go, the implementation of an interface is implicit. There's no need to explicitly specify that structures adhere to a particular interface, as required in some other programming languages. To establish a data type as implementing an interface in Go, it suffices to implement the methods defined by that interface

Since the Human and Animal structures implement the Person interface, we can define the variables of this interface by passing them the structure objects:

var john Person = Human{}
var tiger Person = Animal{}

Where can interfaces help us? Interfaces allow you to define some kind of generic implementation without being tied to a specific type.