定义
把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口
举例
接口Phone, 有一个函数call
type Phone interface {
call()
}
定义2个strct
type NokiaPhone struct {
}
type Samsung struct {
}
实现接口中的call()函数
func (nokiaPhone NokiaPhone) call() {
fmt.Println("I'm NokiaPhone, call.....")
}
func (samsung Samsung) call() {
fmt.Println("I'm Sumsung, call........")
}
测试
var phone Phone
phone = new(NokiaPhone)
fmt.Printf("%p, %T", phone, phone) // %p 输出指针地址,%T 输出类型
phone.call()
phone = new(Samsung)
phone.call()
输出
0x121bf38, *basicTest.NokiaPhone I'm NokiaPhone, call..... I'm Sumsung, call........
注意:new 得到的是个指针
来源:https://www.cnblogs.com/kaituorensheng/p/12241923.html