go语言 什么是接口

接口

1 什么是接口

把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口

接口定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了该接口

2 接口的定义

/* 定义接口 */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* 定义结构体 */
type struct_name struct {
   /* variables */
}

/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* 方法实现*/
}

3 接口代码实现

package main

import "fmt"

// Animal 接口实现  接口实现了 move和eat两个方法
type Animal interface {
	move()
	eat(food string)
}

// Cat 定义猫的结构体
type Cat struct {
	name string
	feet uint8
}

func (c Cat) move() {
	fmt.Printf("%s跑了。。。\n", c.name)
}

func (c Cat) eat(food string) {
	fmt.Printf("%s吃%s\n", c.name, food)
}

// Chicken 定义鸡的结构体
type Chicken struct {
	name string
	feet uint8
}

func (c Chicken) move() {
	fmt.Printf("%s跑了。。。\n", c.name)
}

func (c Chicken) eat(food string) {
	fmt.Printf("%s吃%s\n", c.name, food)
}

func main() {
	var am Animal
	am = Cat{name: "小猫", feet: 4}
	am.move()
	am.eat("老鼠")

	am = Chicken{
		name: "小鸡",
		feet: 2,
	}
	am.move()
	am.eat("小虫子")
}
posted @ 2022-03-10 17:28  三叶草body  阅读(31)  评论(0)    收藏  举报