DEV Community

jguo
jguo

Posted on

Learning Golang 106

Interface

Interfaces are a contract to help us manage types.
define an interface

type bot interface{
   getGreeting() string
}

Enter fullscreen mode Exit fullscreen mode

Unlike other languages, you need to implement interface explicit. Go uses implicit implementation. As long as you define the same method, it will automatically implement the interface.
For example, englishBot and spanishBot are automatically implemented bot.

import (
    "fmt"
)

type bot interface {
    getGreeting() string
}

type englishBot struct {}
type spanishBot struct {}

func (englishBot) getGreeting()string {
    return "Hello!"
}

func (spanishBot) getGreeting() string {
    return "Hola!"
}

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


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

    printGreeting(eb)
    printGreeting(sb)
}
Enter fullscreen mode Exit fullscreen mode

Note, if a interface has multiple functions. To implement the interface, you need to implement all the functions.

Embedding

Go has the ability to “borrow” pieces of an implementation by embedding types within a struct or interface.

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

// ReadWriter is the interface that combines the Reader and Writer interfaces.
type ReadWriter interface {
    Reader
    Writer
}

Or
// ReadWriter stores pointers to a Reader and a Writer.
// It implements io.ReadWriter.
type ReadWriter struct {
    reader *Reader
    writer *Writer
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)