Monday, March 15, 2021

Interfaces

Purpose of Interfaces

Do we need different functions whose only difference is the type of values they receive? Hell no!


Thats the problem interfaces are solving.

Example

In order for a function or type to satisfy an interface, it must adhere with what the interface defined.


package main

import "fmt"

type bot interface {
    getGreeting() string
}

type englishBot struct{}
type spanishBot struct{}

func main() {
    eb := englishBot{}
    sb := spanishBot{}

    printGreeting(eb)
    printGreeting(sb)
}

func printGreeting(b bot) {
    fmt.Println(b.getGreeting())
}

func (englishBot) getGreeting() string {
    // very custom logic for generating english greeting
    return "Hi there!"
}

func (spanishBot) getGreeting() string {
    // very custom logic for generating spanish greeting
    return "Hola!"
}


Rules


NOTE Some interface in standard libraries has this format

Other information about interfaces


  • Implicit - no need to use keywords such as “extends” or “implements”

1 comment:

  1. Source:
    Go: The Complete Developer's Guide (Golang) by Stephen Grider

    ReplyDelete