Go interface satisfaction (接口 满足)最简教程

引言

经典的《Go程序设计语言》是一本好书,很多概念都讲的非常清晰,但是这又是一本比较深的书,很多例子对于我这样的初学者有点复杂了。在我看来Interface是Go代码重用的一个非常好的设计,从PHP过来的人肯定体会到过有些重复是可以避免的。Go设计的Interface就是要免掉一些重复。有人说好的设计应该是面向接口的设计。《Go程序设计语言》中的介绍的Interface的例子有点看不明白,自己写一个代码。

场景

开学了,几个老师和一群学生都要进行自我介绍,当然我们规定他们做机械化介绍,免掉一些自由发挥。先设置老师和学生的type,然和两个类别都定义 introduce_self()函数

type Student struct{
    name string
    age int
    grade int
}

type Teacher struct{
    name string
    age int
    band int
}

func (s Student) introduce_self() string{
    return "my name is " + s.name + " I am a student"
} 

func (t Teacher) introduce_self() string{
    return "my name is " + t.name + " I am s teacher"
}

Interface 定义及应用

定义接口的好处是,用同一个变量名,可以完成不同类型对象的行为控制,对于数组(或切片)迭代,是最为实用的。

type talkable interface{   // 定义接口名称
    introduce_self() string
}

func self_talk(p talkable) string { // 定义接口类型的变量p
    return p.introduce_self()
}

func main(){
...
    var jhon = Student{"John",12,4}
    var rose = Teacher{"Carol", 35,1}
    var words []string

    words=append(words, self_talk(jhon) )
// 在调用self_talk时,隐含了 接口满足表达式,  p=john
// 也就是 jhon 满足p接口,也就是jhon 含有p接口中定义的方法
...
}

完整的,可以通过编译的代码

package main
import(
    "fmt"
)
type talkable interface{
    introduce_self() string
}

type Student struct{
    name string
    age int
    grade int
}

type Teacher struct{
    name string
    age int
    band int
}

func (s Student) introduce_self() string{
    return "my name is " + s.name + " I am a student"
} 

func (t Teacher) introduce_self() string{
    return "my name is " + t.name + " I am s teacher"
}

func self_talk(p talkable) string {
    return p.introduce_self()
}

func main(){
    
    var jhon = Student{"John",12,4}
    var rose = Teacher{"Carol", 35,1}
    var words []string

    words=append(words, self_talk(jhon) )
    words=append(words, self_talk(rose))

    var people []talkable // 接口类型的数组切片,只要对象满足talkabe,就可以填入
    people =append(people, Student{"Tom",13,3})
    people =append(people, Teacher{"Richard",40,1})

    for i:=0;i<len(people);i++{
        words=append(words, self_talk(people[i]) )
    }
    
    for i:=0;i<len(words);i++{
        fmt.Printf("%d,%s\n",i+1,words[i])
    }

}

本篇完

初学者,请多指教
原创内容,转载请注明 copywrite threadtag

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容