go的interface疑问
点击查看代码
package main
import "fmt"
type Animal interface{
Talk()
Eat()
Name() string
}
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{
// .\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("%v, %#v %T, %p \n", a,a,a,&a)
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{}
// *(&Dog).Eat() // a存的是一个值类型的Dog,那么调用a.Eat(), &Dog-->Eat()之后,如果一个变量存储在接口类型的变量中,那么就不能获取这个变量的地址
a = d1
a.Eat()
fmt.Printf("去你大爷的 %v, %#v %T, %p \n",a, a,a,&a)
//aa := "1"
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()
}
输出:
点击查看代码
正在吃骨头
汪汪汪
名字叫旺财
猪正在吃
-----------------------1111------------------------------------------------
猪正在吃
嗯呢嗯
名字叫旺财猪
-----------------------------------------------------------------------
正在吃骨头
去你大爷的 &{}, &main.Dog{} *main.Dog, 0xc0001041e0
去你大爷的aa {}, main.Dog{} main.Dog, 0xc0001041e0
狗是胎生的
写入自己的博客中才能记得长久