Published on

Interface

Authors
  • avatar
    Name
    Galuh Pradipta
    Twitter

Golang Interface

An interface in Golang is a collection of method signatures defined by the user. It is a way to achieve polymorphism in Golang.

The interface type is defined using the type keyword followed by the interface name and the keyword interface.

Here is an example of how to define an interface in Golang:

type Animal interface {
   Sound() string
   Move() string
}

This defines an interface called Animal with two method signatures Sound() and Move().

To implement this interface, a struct can be defined with the same method signatures as the interface. For example:

type Dog struct {
   Name string
}

func (d Dog) Sound() string {
   return "Woof!"
}

func (d Dog) Move() string {
   return "Running"
}

The Dog struct implements the Animal interface by defining the Sound() and Move() methods.

Now, a variable of type Animal can hold any struct that implements the Animal interface. For example:

var a Animal
a = Dog{"Fido"}
fmt.Println(a.Sound()) // Output: Woof!
fmt.Println(a.Move()) // Output: Running

In conclusion, Golang interfaces are a powerful way to achieve polymorphism in Golang by defining a collection of method signatures that can be implemented by any struct.