文章目录
定义接口
// interface 本质是个指针
type AnimateInterface interface {
Sleep()
GetColor() // 动物的颜色
GetType() // 动物类型
}
实现具体的类,需要全部实现接口的方法
type Cat struct {
color string // 动物颜色
}
func (this *Cat) Sleep() {
fmt.Println("cat sleep = ", this)
}
func (this *Cat) GetColor() {
fmt.Println("Get Color = ", this)
}
func (this * Cat) GetType() {
fmt.Println("Get Type = ", this)
}
万能接口interface{},和类型断言
// arg 可以是任何类型的数据
func Test(arg interface{}) {
fmt.Println("interface arg = ", arg);
value, ok := arg.(string)
if !ok {
fmt.Println("arg is not string type ", value);
}
}
Test(100)
Test("name")
type Book struct {
idsn string
name string
}
var book = Book{"111--222", "Golang"}
Test(book)