前言

If it looks like a duck and quacks like a duck, it’s a duck.

Golang 的 interface 是一種 duck typing 的實現。在 duck typing 中,我們關心的是物件的行為而不是物件的類型。

範例

定義兩個 struct 及其 function

type Duck struct {
  Name string
}

type Cat struct {
  Name string
}

func (d *Duck) Eat() {
  fmt.Printf("%s is eating\n", d.Name)
}

func (d *Duck) Run() {
  fmt.Printf("%s is running with two feet\n", d.Name)
}

func (d *Duck) Noise() {
  fmt.Printf("%s is quacking\n", d.Name)
}

func (c *Cat) Eat() {
  fmt.Printf("%s is eating\n", c.Name)
}

func (c *Cat) Run() {
  fmt.Printf("%s is running with four legs\n", c.Name)
}

func (c *Cat) Noise() {
  fmt.Printf("%s is meowing\n", c.Name)
}

定義 interface 及其 function

type Animal interface {
  Eat()
  Run()
  Noise()
}

建立三個參數型別為 Animal 的 function

func ShowEat(animal Animal) {
  animal.Eat()
}

func ShowRun(animal Animal) {
  animal.Run()
}

func MakeNoise(animal Animal) {
  animal.Noise()
}

initialize struct

var duck = Duck{Name: "Moe"}
var cat = Cat{Name: "Sassy"}

呼叫 function

ShowEat(&duck)
ShowRun(&duck)
MakeNoise(&duck)

ShowEat(&cat)
ShowRun(&cat)
MakeNoise(&cat)

輸出

$ go run .
Moe is eating
Moe is running with two feet
Moe is quacking
Sassy is eating
Sassy is running with four legs
Sassy is meowing

Gist