摘要:今天我们来学习 Golang 中的 interface 类型。
Go 的 5 个关键点
interface 是一种类型
type Animal interface { SetName(string) GetName() string }
首先 interface 是一种类型,从它的定义中就可以看出用了 type 关键字,更准确的说 interface 是一种具有一组方法的类型,这些方法定义了 interface 的行为。Go 允许不带任何方法的 interface, 这种类型的 interface 叫 empty interface。如果一个类型实现了一个 interface 中所有的方法,我们说该类型实现了该 interface, 所以所有类型都实现了 empty interface, Go 没有显式的关键字用来实现 interface, 只需要实现 interface 包含的方法即可。
interface 变量存储的是实现者的值
package main import ( "fmt" ) type Animal interface { SetName(string) GetName() string } type Cat struct { Name string } func (c Cat) SetName(name string) { fmt.Println("c addr in: ", c) c.Name = name fmt.Println(c.GetName()) } func (c Cat) GetName() string { return c.Name } func main() { // c := &Cat{Name: "Cat"} // fmt.Println("c addr out: ", c) // c.SetName("DogCat") // fmt.Println(c.GetName()) c := Cat{} var i Animal i = &c //把变量赋值给一个 interface fmt.Println(i.GetName()) }