go接口

点击查看代码
package main

import "fmt"

type Animal interface{
	Talk()
	Eat()
	Name() string  //string 是方法返回的类型
}

type Describle interface{
	Describle() 
}

type AvanceAnimal interface{
	Animal
	Describle
}
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("d>> %v, %#v, %T, %p\n", d,d,d,&d)
	fmt.Printf("a赋值之前>> %v,%#v, %T, %p\n", a,a,a,&a)

	a = d
	fmt.Printf("a赋值之后>> %v, %T, %p\n", a,a,&a)
	a.Eat()
	a.Talk()
	a.Name()

	var p Pig
	a  = p
	a.Eat()
	a.Talk()
	a.Name()
	fmt.Println("-----------------------------------------------------------------------")
	var d1 *Dog = &Dog{}
	//*(&Dog).Eat() // a存的是一个值类型的Dog,那么调用a.Eat(), &Dog-->Eat()之后,如果一个变量存储在接口类型的变量中,那么就不能获取这个变量的地址
	a = d1
	a.Eat()

	var b PuruDongWu
	b = d
	b.TaiSheng()
}


func just(a Animal){
	/*v1 := a.(type)  //不知道为啥,不能在switch外部做a.(type)
	fmt.Printf("这是v%#v==%v==%T",v1,v1,v1)*/
	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()
	fmt.Printf("---------------分割线----------------")
	testInterface2()

}

输出:

点击查看代码
d>> {}, main.Dog{}, main.Dog, 0x59f578
a赋值之前>> <nil>,<nil>, <nil>, 0xc0000361f0
a赋值之后>> {}, main.Dog, 0xc0000361f0
正在吃骨头
汪汪汪
名字叫旺财
猪正在吃
嗯呢嗯
名字叫旺财猪
-----------------------------------------------------------------------
正在吃骨头
狗是胎生的
---------------分割线----------------v is dog,{}
v is pig,{}

posted @ 2022-03-07 22:08  ty1539  阅读(23)  评论(0编辑  收藏  举报