Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法
就是实现了这个接口。
//接口定义
type interface_name interface{
method_1[return_type]
method_2[return_type]
method_3[return_type]
method_4[return_type]
}
//结构体定义
type struct_name struct{
value1 type1;
...
}
//接口实现
type (struct_name_val struct_name)method_1()[return_type]{
}
...go
type Cat interface {
yell()
}
type orangeCat struct {
}
func (orangecat orangeCat) yell() {
fmt.Println("miao!")
}
type blackCat struct {
}
func (blackcat blackCat) yell() {
fmt.Println("miaowu!")
}
func main(){
var cat Cat
cat = new(orangeCat)
cat.yell()
cat = new(blackCat)
cat.yell()
}