interface 接口 -Go 学习记录

Go interface

基本概念和语法

  • 通过关键字type和interface,声明出接口类 type TestInterface interface {}
  • 因为接口类型与其他数据类型不同,它是没法被实例化的。既不能通过调用new函数或make函数创建出一个接口类型的值
  • 我们通过 interface 来定义对象的一组行为方法,如果某个对象实现了某个接口类型的所有方法,则此对象就是这个接口的实现类型

接口类型实现规则

  1. 两个方法的签名需要完全一致
  2. 两个方法的名称要一模一样

代码实现:

type Pet interface {
    SetName(name string)
    Name() string
    Category() string
}

type Dog struct {
    name string
}

func (dog *Dog) SetName(name string) {
    dog.name = name
}

func (dog Dog) Name() string {
    return dog.name
}

func (dog Dog) Category() string {
    return "dog"
}

func TestDog(t *testing.T) {
    dog := Dog{"little pig"}
    _, ok := interface{}(dog).(Pet)
    fmt.Printf("Dog implements interface Pet: %v\n", ok) // Dog implements interface Pet: false
    _, ok = interface{}(&dog).(Pet)
    fmt.Printf("*Dog implements interface Pet: %v\n", ok) // *Dog implements interface Pet: true
    var pet Pet = &dog
    fmt.Printf("This pet is a %s, the name is %q.\n",
        pet.Category(), pet.Name()) //  This pet is a dog, the name is "little pig".

    dog.SetName("monster")
    fmt.Printf("This pet is a %s, the name is %q.\n",
        pet.Category(), pet.Name()) // This pet is a dog, the name is "monster".
}

如想看学习记录同步的练习代码移步 GitHub

本作品采用《CC 协议》,转载必须注明作者和本文链接
微信搜索:上帝喜爱笨人
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!