go语言接口的使用

interface是一种类型 。一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节。

一种类型多种接口

type sayer interface {
	 say ()
}

type  mover  interface {
	move()
}

type  fooder interface {
	food()
}

type   dog struct {
	name string
}

func (d dog )  say()  {
	fmt.Println("说话:",d.name)
}

func  (d dog) move(){
	fmt.Println("移动: ",d.name)
}


func (d * dog) food (){
	  fmt.Println( "食物:",d.name)
}


func main() {
	var x sayer
	var y mover
	var z  fooder

	a := dog{name: "hello",}
	x = a
	x.say()

	b := dog{name: "shanghai",}
	y = b
	y.move()

	c := dog{name: "gouliang",}
   z = &c
   z.food()
}

多种类型一种接口:

 type  mover interface {
 	Move()
 }

 type  dog struct {
 }

 type  car struct {

 }
 func (d dog) Move(){
    fmt.Println("百公里加速,只要一碗饭")
 }

 func (c car ) Move(){
	 fmt.Println("百公里加速,只要一箱油")
 }
func main() {
	var x mover
	x  = dog{}
	x.Move()
	x = car{}
	x.Move()
}

 接口可以使用断言来进行判断:

func justifyType(x interface{}){
	switch v := x.(type){
	case string:
		fmt.Printf("x is a string,value is %v\n", v)
	case int:
		fmt.Printf("x is a int is %v\n", v)
	case bool:
		fmt.Printf("x is a bool is %v\n", v)
	default:
		fmt.Println("unsupport type!")
	}
}

空接口判断:

对比有值的

猜你喜欢

转载自blog.csdn.net/weixin_44282540/article/details/114926508