go 接口,方法,type验证
package main
import "fmt"
type Animal interface{
Talk()
Eat()
Name() string
}
type A1 interface{}
type Dog struct{}
func (d Dog) Talk(){
fmt.Println("汪汪汪")
}
func (d Dog) Eat(){
fmt.Println("正在吃骨头")
}
func (d Dog) Name() string{
fmt.Println("名字叫旺财")
return "旺财"
}
type Pig struct{}
func (p Pig) Talk(){
fmt.Println("嗯呢嗯")
}
func (p Pig) Eat(){
fmt.Println("猪正在吃")
}
/*func (p *Pig) Name() string{
fmt.Println("名字叫旺财猪112")
return "旺财猪13"
// .\main.go:90:6: cannot use p (type Pig) as type Animal in argument to just:
// Pig does not implement Animal (Eat method has pointer receiver)
//指针类型实现了这个接口的方法,不能放入值类型数据
}*/
func (p Pig) Name() string{
fmt.Println("名字叫旺财猪")
return "旺财猪"
}
type PuruDongWu interface{
TaiSheng()
}
func (d Dog) TaiSheng(){
fmt.Println("狗是胎生的")
}
func testInterface1(){
var d Dog
var a Animal
fmt.Printf("testInterface1 00> %v, %#v %T, %p \n", a,a,a,&a)
fmt.Printf("testInterface1 01> %v, %#v %T, %p \n", d,d,d,&d)
a = d
a.Eat()
a.Talk()
a.Name()
var p Pig
a = p
p.Eat()
fmt.Println("-----------------------1111------------------------------------------------")
a.Eat()
a.Talk()
a.Name()
fmt.Println("-----------------------------------------------------------------------")
var d1 *Dog = &Dog{}
d1.Eat()
d1.Talk()
d1.Name()
(*d1).Eat()
(*d1).Talk()
(*d1).Name()
fmt.Println("-----------------------d1 *Dog = &Dog{}------------------------------------------------")
//*(&Dog).Eat() // a存的是一个值类型的Dog,那么调用a.Eat(), &Dog-->Eat()之后,如果一个变量存储在接口类型的变量中,那么就不能获取这个变量的地址
a = d1
a.Eat()
a.Talk()
a.Name()
fmt.Printf("去你大爷的 %v, %#v %T, %p \n",a, a, a, &a)
var a1 A1
a1 = 3333
fmt.Println(a1)
a = d // 接口只能存储实现了该接口方法的对象
fmt.Printf("去你大爷的aa %v, %#v %T, %p \n", a, a, a, &a)
var b PuruDongWu
b = d
b.TaiSheng()
}
func just(a Animal){
switch v := a.(type){
case Dog:
fmt.Printf("v is dog %v\n",v)
case Pig:
fmt.Printf("v is pig %v\n",v)
default:
fmt.Println("not support type")
}
}
func testInterface2(){
var d Dog
just(d)
var p Pig
just(p)
}
func main() {
testInterface1()
testInterface2()
}
接口:
testInterface1 00> <nil>, <nil> <nil>, 0xc0000361f0
testInterface1 01> {}, main.Dog{} main.Dog, 0x59f578
正在吃骨头
汪汪汪
名字叫旺财
猪正在吃
-----------------------1111------------------------------------------------
猪正在吃
嗯呢嗯
名字叫旺财猪
-----------------------------------------------------------------------
正在吃骨头
汪汪汪
名字叫旺财
正在吃骨头
汪汪汪
名字叫旺财
-----------------------d1 *Dog = &Dog{}-----------------------------------------
-------
正在吃骨头
汪汪汪
名字叫旺财
去你大爷的 &{}, &main.Dog{} *main.Dog, 0xc0000361f0
3333
去你大爷的aa {}, main.Dog{} main.Dog, 0xc0000361f0
狗是胎生的
v is dog {}
v is pig {}
写入自己的博客中才能记得长久