Interface in Go Lang

  • date 7th September, 2022 |
  • by Prwatech |
  • 0 Comments

Golang Interfaces Explained

 
  • Declaring interface type

An Interface is an abstract type. An interface describes all the methods of a method set and provides the signatures for each method. To create an interface, use the interface keyword, followed by curly braces containing a list of method names, along with any parameters or return values the methods are expected to have.  
  • Types that Satisfied an Interface

Defines an interface type named Employee with two methods. Then it defines a type named Emp that satisfies Employee.
// Declare an Interface Type and methods that do not have a body

type Employee interface {
    PrintName() string                // Method with string return type
    PrintAddress(id int)              // Method with int parameter
    PrintSalary(b int, t int) float64 // Method with parameters and return type
}
 
  • Type that Satisfies an Interface
Defines an interface type named Employee with two methods. Then it defines a type named Emp that satisfies Employee. We define all the methods on Emp that it needs to satisfy Employee
package main
import "fmt"

// Employee is an interface for printing employee details
type Employee interface {
    PrintName(name string)
    PrintSalary(basic int, tax int) int
}
// Emp user-defined type
type Emp int

func (e Emp) PrintName(name string) {   	// Print Name method to print employee name
    fmt.Println("Employee Id:\t", e)
    fmt.Println("Employee Name:\t", name)
}

func (e Emp) PrintSalary(basic int, tax int) int {          // Print Salary method to calculate employee salary
    var salary = (basic * tax) / 100
    return basic - salary
}

func main() {
    var e1 Employee
    e1 = Emp(2332)
    e1.PrintName("Sandeep Sharma")
    fmt.Println("Employee Salary:", e1.PrintSalary(30000, 5))
}
Output :
PS C:\GO_Language\interface> go  run interface.go
Employee Id:     2332
Employee Name:   Sandeep Sharma
Employee Salary: 28500
 
  • Type that Satisfies Multiple Interfaces
Interfaces allow any user-defined type to satisfy multiple interface types at once.
package main
import "fmt"

type Vehicle interface {
    Structure() []string
    Speed() string
}
    
type Human interface {
    Structure() []string
    Performance() string
}

type Car string

func (c Car) Structure() []string {
    var parts = []string{"ECU", "Engine", "Air Filters", "Wipers", "Gas Task"}
    return parts
}

func (c Car) Speed() string {
    return "200 Km/Hrs"
}

type Man string

func (m Man) Structure() []string {
    var parts = []string{"Brain", "Heart", "Nose", "Eyelashes", "Stomach"}
    return parts
}

func (m Man) Performance() string {
    return "8 Hrs/Day"
}

func main() {
    var BMW Vehicle
    BMW = Car("World Top Brand")

    var labour Human
    labour = Man("Software Developer")

    for i, j := range bmw.Structure() {
        fmt.Printf("%-15s :    %15s\n", j, labour.Structure()[i])
    }
}
Output :
PS C:\GO_Language\interface> go  run interface2.go

ECU             :              Brain
Engine          :              Heart
Air Filters     :               Nose
Wipers          :          Eyelashes
Gas Task        :            Stomach
 
  • Interface Accepting Address of the Variable
The Print() methods accept a receiver pointer. Hence, the interface must also accept a receiver pointer.
package main
import "fmt"

type Book struct {
    author, title string
}

type Magazine struct {
    title string
    issue int
}

func (b *Book) Assign(n, t string) {
    b.author = n
    b.title = t
}
func (b *Book) Print() {
    fmt.Printf("Author: %s, Title: %s\n", b.author, b.title)
}

func (m *Magazine) Assign(t string, i int) {
    m.title = t
    m.issue = i
}
func (m *Magazine) Print() {
    fmt.Printf("Title: %s, Issue: %d\n", m.title, m.issue)
}

type Printer interface {
    Print()
}

func main() {
    var b Book                                 // Declare an instance of Book
    var m Magazine                             // Declare instance of Magazine
    b.Assign("Jack Rabbit", "Book of Rabbits")                 // Assign values to b via method
    m.Assign("Rabbit Weekly", 26)              // Assign values to m via method

    var i Printer 			// Declare variable of interface type
    fmt.Println("Call interface")
    i = &b  			  // Method has pointer receiver, interface does not
    i.Print() 			// Show book values via the interface
    i = &m    			// Magazine also satisfies shower interface
    i.Print() 			// Show magazine values via the interface
}
Output :
PS C:\GO_Language\interface> go  run interface3.go
Call interface
Author: Jack Rabbit, Title: Book of Rabbits
Title: Rabbit Weekly, Issue: 26
 
  • Empty Interface Type

The types interface{} is known as the empty interface, and it is use to accept values of any type. The empty interface doesn't have any methods that are require to satisfy it, and so every type satisfies it.
package main
import "fmt"

func printType(i interface{}) {
    fmt.Println(i)
}

func main() {
    var manyType interface{}
    manyType = 100
    fmt.Println(manyType)

    manyType = 200.50
    fmt.Println(manyType)

    manyType = "India"
    fmt.Println(manyType)

    printType("Go programming language")
    var countries = []string{"India", "Japan", "Canada", "Australia", "Russia"}
    printType(countries)

    var employee = map[string]int{"Mark": 10, "Sandy": 20}
    printType(employee)

    country := [3]string{"Japan", "Australia", "Germany"}
    printType(country)
}
Output :
PS C:\GO_Language\interface> go  run interface4.go
100
200.5
India
Go programming language
[india japan canada australia russia]
map[Mark:10 Sandy:20]
[Japan Australia Germany]
 
  • Polymorphism
Polymorphism is the ability to write code that can take on different behaviour through the implementation of types. We have the declaration of a struct named Pentagon, Hexagon, Octagon, and Decagon with the implementation of the geometry interface.
    package main

import (
    "fmt"
)

// Geometry is an interface that defines Geometrical Calculation
type Geometry interface {
    Edges() int
}

// Pentagon defines a geometrical object
type Pentagon struct{}

// Hexagon defines a geometrical object
type Hexagon struct{}

// Octagon defines a geometrical object
type Octagon struct{}

// Decagon defines a geometrical object
type Decagon struct{}

// Edges implements the geometry interface
func (p Pentagon) Edges() int { return 5 }

// Edges implements the geometry interface
func (h Hexagon) Edges() int { return 6 }

// Edges implements the geometry interface
func (o Octagon) Edges() int { return 8 }

// Edges implements the geometry interface
func (d Decagon) Edges() int { return 10 }

// Parameter calculates the parameter of an object
func Parameter(geo Geometry, value int) int {
    num := geo.Edges()
    calculation := num * value
    return calculation
}

// main is the entry point for the application. 
func main() {
    p := new(Pentagon)
    h := new(Hexagon)
    o := new(Octagon)
    d := new(Decagon)

    g := [...]Geometry{p, h, o, d}

    for _, i:= range g {
        fmt.Println(Parameter(i, 5))
    }
}
Output :
PS C:\GO_Language\interface> go  run poly.go      

25
30
40
50
Golang Interfaces Explained

Quick Support

image image