Usage of interface in Go

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.


Another working example showing the interaction between an interface and a structure

package main

import "fmt"

type Info interface {
Noofchar() int
Increment()
}

type Testinfo struct {
noofchar int     
}

func (x *Testinfo) Noofchar() int {
return x.noofchar
}
func (x *Testinfo) Increment() {
x.noofchar++
}

func main(){
var t Info = &Testinfo{noofchar:1}
fmt.Println("No of char ",t.Noofchar())
t.Increment()
fmt.Println("No of char ",t.Noofchar())
}