Interface in Object Oriented Programming in Golang

Create new folder named entities. In entities folder, create new entities as below:

In entities folder, create new file named animal.go as below:

package entities

type Animal interface {
	Sound() string
}

In entities folder, create new file named dog.go as below:

package entities

type Dog struct {
}

func (dog Dog) Sound() string {
	return "the dog barks"
}




In entities folder, create new file named cat.go as below:

package entities

type Cat struct {
}

func (cat Cat) Sound() string {
	return "the dog meows"
}

Create new folder named src. In src folder, create new file named main.go as below:

package main

import (
	"entities"
	"fmt"
)

func main() {

	var animal entities.Animal
	dog := entities.Dog{}
	cat := entities.Cat{}

	animal = dog
	fmt.Println(animal.Sound())

	animal = cat
	fmt.Println(cat.Sound())

}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

the dog barks
the dog meows