Welcome To Golang By Example

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

Inner Working or Internals of an Interface in Go (Golang)

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

Table of Contents

  • Overview
  • Code

Overview

Like any other variable, an interface variable is represented by a type and value. Interface value, in turn under the hood consists of two tuple

  • Underlying Type
  • Underlying Value

See below diagram which illustrates what we mentioned above

Let’s see an example and then we can create a similar diagram as above for that example.

Assume we have an interface animal as below

type animal interface {
    breathe()
    walk()
}

We also have a lion struct implementing this animal interface

type lion struct {
    age int
}

Code

package main

import "fmt"

type animal interface {
    breathe()
    walk()
}

type lion struct {
    age int
}

func (l lion) breathe() {
    fmt.Println("Lion breathes")
}

func (l lion) walk() {
    fmt.Println("Lion walk")
}

func main() {
    var a animal
    a = lion{age: 10}
    a.breathe()
    a.walk()
}

Output

Lion breathes
Lion walk

For the above case,  lion struct implementing the animal interface would be like below

Golang provides format identifiers to print the underlying type and underlying value represented by the interface value.

  • %T can be used to print the concrete type of the interface value
  • %v can be used to print the concrete value of the interface value.
package main

import "fmt"

type animal interface {
    breathe()
    walk()
}

type lion struct {
    age int
}

func (l lion) breathe() {
    fmt.Println("Lion breathes")
}

func (l lion) walk() {
    fmt.Println("Lion walk")
}

func main() {
    var a animal
    a = lion{age: 10}
    fmt.Printf("Underlying Type: %T\n", a)
    fmt.Printf("Underlying Value: %v\n", a)
}

Output

Concrete Type: main.lion
Concrete Value: {10}
  • 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