Fragment Description:



The idea behind go interfaces is duck typing.
Which simply translates into:
If you look like a duck and quack like a duck then you are a duck.
Meaning that if your object implements all duck's features then there should be no problem using it as a duck.
Below is an example.
Here a Human is a Walker and a Dog is a Walker.
Why? Because they both..
well...
Walk.
They both implement the Walk () string function.
So this is why you can execute MakeWalk on them.
This is very helpful when you want different types to behave in the same manner.
A practical example would be file type objects (sockets, file objects) - you need a Write and a Read function on all of them.
Then you can use Write and Read in the same fashion independent of their type - which is cool.


walkerInterface

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:36

/* ... <== see fragment description ... */

package main

import (
    "fmt"
)

type Walker interface {
    Walk() string
}
type (
    Human string
    Dog   string
)

func (human Human) Walk() string { //A human is a walker
    return "I'm a man and I walk!"
}
func (dog Dog) Walk() string { //A dog is a walker
    return "It is a dog and it walks!"
}

// Make a walker walk (any type that implement Walker can be a parm here)
// ====>
func MakeWalk(w Walker) {
    fmt.Printf("MakeWalk is saying: %q\n", w.Walk())
}

var (
    human Human
    dog   Dog
)

func main() {
    MakeWalk(human)
    MakeWalk(dog)
}

/* Expected Output:
MakeWalk is saying: "I'm a man and I walk!"
MakeWalk is saying: "It is a dog and it walks!"
*/



Comments