引言
經(jīng)典的《Go程序設(shè)計(jì)語言》是一本好書,很多概念都講的非常清晰基括,但是這又是一本比較深的書蛇受,很多例子對于我這樣的初學(xué)者有點(diǎn)復(fù)雜了野来。在我看來Interface是Go代碼重用的一個(gè)非常好的設(shè)計(jì),從PHP過來的人肯定體會(huì)到過有些重復(fù)是可以避免的疾牲。Go設(shè)計(jì)的Interface就是要免掉一些重復(fù)植捎。有人說好的設(shè)計(jì)應(yīng)該是面向接口的設(shè)計(jì)⊙羧幔《Go程序設(shè)計(jì)語言》中的介紹的Interface的例子有點(diǎn)看不明白焰枢,自己寫一個(gè)代碼。
場景
開學(xué)了舌剂,幾個(gè)老師和一群學(xué)生都要進(jìn)行自我介紹济锄,當(dāng)然我們規(guī)定他們做機(jī)械化介紹,免掉一些自由發(fā)揮霍转。先設(shè)置老師和學(xué)生的type荐绝,然和兩個(gè)類別都定義 introduce_self()函數(shù)
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 定義及應(yīng)用
定義接口的好處是,用同一個(gè)變量名谴忧,可以完成不同類型對象的行為控制很泊,對于數(shù)組(或切片)迭代,是最為實(shí)用的沾谓。
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) )
// 在調(diào)用self_talk時(shí)委造,隱含了 接口滿足表達(dá)式, 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 // 接口類型的數(shù)組切片昏兆,只要對象滿足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])
}
}
本篇完
初學(xué)者,請多指教
原創(chuàng)內(nèi)容妇穴,轉(zhuǎn)載請注明 copywrite threadtag