Welcome To Golang By Example

Non-struct Custom Type Implementing an interface in Go (Golang)

Table of Contents

Overview

It is also perfectly ok for any non-struct custom type to implement an interface. Let’s see an example

Assume we have an interface animal as below

type animal interface {
    breathe()
    walk()
}

Code

package main

import "fmt"

type animal interface {
	breathe()
	walk()
}

type cat string

func (c cat) breathe() {
	fmt.Println("Cat breathes")
}

func (c cat) walk() {
	fmt.Println("Cat walk")
}

func main() {
	var a animal

	a = cat("smokey")
	a.breathe()
	a.walk()
}

Output

Cat breathes
Cat walk

The above program illustrates the concept that any custom type can also implement an interface. The cat is of string type and it implements the breathe and walk method hence it is correct to assign an instance of cat type to a variable of animal type.