Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Type Implementing multiple interfaces in Go (Golang)

Posted on July 18, 2020July 18, 2020 by admin

Table of Contents

  • Overview
  • Code

Overview

A type implements an interface if it defines all methods of an interface. If that type defines all methods of another interface then it implements that interface. In essence, a type can implement multiple interfaces.

Let’s see an example

Assume we have an interface animal as below

type animal interface {
    breathe()
    walk()
}

Also let’s say we have a mammal interface too as below

type mammal interface {
    feed()
}

We also have a lion struct implementing this animal and mammal interface

type lion struct {
    age int
}

Code

package main

import "fmt"

type animal interface {
    breathe()
    walk()
}

type mammal interface {
    feed()
}

type lion struct {
     age int
}
func (l lion) breathe() {
    fmt.Println("Lion breathes")
}
func (l lion) walk() {
    fmt.Println("Lion walk")
}
func (l lion) feed() {
    fmt.Println("Lion feeds young")
}
func main() {
    var a animal
    l := lion{}
    a = l
    a.breathe()
    a.walk()
    
    var m mammal
    m = l
    m.feed()
}

Output

Lion breathes
Lion walk
Lion feeds young

In the above program, the lion struct defines all methods of animal interface. It also defines all methods of mammal interface. That is why this works

var a animal
l := lion{}
a = l
a.breathe()
a.walk()

as well as this works

var m mammal
m = l
m.feed()
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme