Go语言中的接口不是Java面向对象的那个接口,而是一种数据类型。但Go的接口多多少少继承了面向对象的那个接口的概念。笔者认为接口、结构体以及实现接口的方法三者组合起来,就能够实现面向对象。
Go语言定义了新的数据类型接口(Interface)。Go语言的接口会将所有具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了该接口。
Go语言中的接口类型有如下特性:
接口定义使用interface
关键字,语法如下:
// interface defintion
type interface_name interface {
method_name1 [return_type1]
method_name2 [return_type2]
method_name3 [return_type3]
...
method_namen [return_typen]
}
// struct defintion
type struct_name struct {
}
// implement interface
func (struct_name_variable1 struct_name) method_name1() [return_type1] {
//method implementation
}
func (struct_name_variable2 struct_name) method_name2) [return_type2] {
//method implementation
}
该例说明,普通的方法定义和用于实现接口的方法的定义是不一样的。
实例如下:
package main
import "fmt"
type Phone interface {
call() int
}
type ApplePhone struct {
phoneType string
}
type SumsungPhone struct {
phoneType string
}
func (iphone ApplePhone) call() int {
fmt.Println("This is a call from", iphone.phoneType)
return 1
}
func (sphone SumsungPhone) call() int {
fmt.Println("This is a call from", sphone.phoneType)
return 2
}
func main() {
iphone := ApplePhone{"iphone"}
sphone := SumsungPhone{"Sumsung"}
fmt.Println(iphone.call())
fmt.Println(sphone.call())
}
// This is a call from iphone
// 1
// This is a call from Sumsung
// 2
在该例中,只有方法显式声明了它实现的是接口中的哪一个方法,其余都没有显式声明,但却实现了接口、结构体、方法三者的动态绑定。Go语言内置了这种绑定的实现。interface
实现的底层原理留坑待填。
可以使用interface.(type)
判断接口实际类型。
package main
import (
"fmt"
)
type Phone interface {
call() int
}
type ApplePhone struct {
phoneType string
}
type SumsungPhone struct {
phoneType string
}
func (iphone ApplePhone) call() int {
fmt.Println("This is a call from", iphone.phoneType)
return 1
}
func (sphone SumsungPhone) call() int {
fmt.Println("This is a call from", sphone.phoneType)
return 2
}
func main() {
var phone Phone = ApplePhone{"iphone"}
switch phone.(type) {
case ApplePhone:
fmt.Println("This is a ApplePhone")
case SumsungPhone:
fmt.Println("This is a SumSungPhone")
default:
fmt.Println("No match item")
}
}