Open SilenceHVK opened 5 years ago
Go 语言中的接口就是方法签名的集合,接口只有声明,没有实现,没有数据字段。
Structurol Typing
package main import "fmt" // 定义 Usb 接口 type Usb interface { GetName() string Connection() } // 定义 Phone 结构 type Phone struct { Name string } // 实现 Usb 接口的 GetName 方法 func (p Phone) GetName() string { return p.Name } // 实现 Usb 接口的 Connection 方法 func (p Phone) Connection() { fmt.Println("Connection:", p.GetName()) } func main() { iPhone := Phone{Name:"iPhone"} fmt.Println(iPhone.GetName()) // iPhone iPhone.Connection() // Connection:iPhone }
Go 允许不带任何方法签名的接口,这种类型的接口被称为 empty interface,按照第一条结论,只要某个类型拥有了某个接口的所有方法,那么该类型就实现了该接口,所以所有类型都实现了 empty interface;
empty interface
当对象赋值给接口时,会发生拷贝。接口内部存储的是指向这个复制品的指针,无法修改其状态,也无法获取指针;
iPhone := Phone{Name: "iPhone"} var usb = Usb(iPhone) fmt.Println(iPhone.GetName()) // iPhone fmt.Println(usb.GetName()) // iPhone iPhone.Name = "SAMSUNG" fmt.Println(iPhone.GetName()) // SAMSUNG fmt.Println(usb.GetName()) // iPhone
// 定义调用接口方法 func InvokInterface(inter interface{}) { // inter.(type) 用于获取类型 switch t := inter.(type) { case Usb: t.Connection() case string: fmt.Println(t) default: fmt.Println("Unkown") } } function main() { iPhone := Phone{Name: "iPhone"} var usb = Usb(iPhone) hello := "Hello World" const PI = 3.14 InvokerInterface(iPhone) // Connection: iPhone InvokerInterface(usb) // Connection: iPhone InvokerInterface(hello) // Hello World InvokerInterface(PI) // Unkown }
Go 语言中的接口
Go 语言中的接口就是方法签名的集合,接口只有声明,没有实现,没有数据字段。
Structurol Typing
;Go 允许不带任何方法签名的接口,这种类型的接口被称为
empty interface
,按照第一条结论,只要某个类型拥有了某个接口的所有方法,那么该类型就实现了该接口,所以所有类型都实现了empty interface
;当对象赋值给接口时,会发生拷贝。接口内部存储的是指向这个复制品的指针,无法修改其状态,也无法获取指针;