DEV Community


Posted on


Learning Golang 106


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 (

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) {

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

Enter fullscreen mode Exit fullscreen mode

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


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 {

// 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)

Create an Account! πŸ‘€ Just want to lurk?
You can still create an account and turn on features like 🌚 dark mode.