Contents

interface

Interfaces Explained

  1. is a type
  2. contain a set of method signature
  1. 引入一个中间层,调用方和实现方解耦 https://img.draveness.me/golang-interface.png
  1. assertion: 将interface 抓换为 具体类型
1
2
var a interface{} = 100;
var aa,ok = a.(string)
  1. conversions
  1. if methods receiver is value; then value and pointer implement the interface

for pointer, it could get value by dereference; then copy it;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
type Duck interface{ Quack() }

type Cat struct{ Name string }

func (c Cat) Quack() {

	fmt.Println("memo")
	c.Name = "abc"
}
func main() {
	var d Duck = &Cat{"jim"} // 使用结构体初始化变量
	d.Quack()
	fmt.Println(d)

}
  1. if methods receiver is pointer, then only pointer implement the interface

for value receiver, it could not get origin pointer;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type Duck interface{ Quack() }

type Cat struct{ Name string }

func (c *Cat) Quack() {

	fmt.Println("memo")
	c.Name = "abc"
}
func main() {
	var d Duck = Cat{"jim"} // 使用结构体初始化变量
	d.Quack()
	fmt.Println(d)
}
  1. interface with compile time