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)

Want to Create an Account?
Now it's your turn!
Β 
πŸ—’ Share a tutorial
πŸ€” Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.