Search code examples
interfacego

Usage of interface in Go


I would like to understand the interface type with a simple example of it's use in Go (Language).

I read the web documentation, but I don't get it.


Solution

  • 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. Here is an example:

    package main
    
    import (
        "fmt"
    )
    
    type Walker interface {
        Walk() string
    }
    
    type Human string
    type Dog string
    
    func (human Human) Walk() string { //A human is a walker
        return "I'm a man and I walked!"
    }
    
    func (dog Dog) Walk() string { //A dog is a walker
        return "I'm a dog and I walked!"
    }
    
    //Make a walker walk
    func MakeWalk(w Walker) {
        fmt.Println(w.Walk())
    }
    
    func main() {
        var human Human
        var dog Dog
        MakeWalk(human)
        MakeWalk(dog)
    }
    

    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.