Interface

Interface is a group of method signatures, continuin with the example before, if Student realize three methods:

SayHi,Sing,BorrowMoney,while Employee realize SayHi,Sing,SpendSalary, the combination of those methods is defined as interface.

Here SayHi and Sing are realized by both structs, so those two structs belong to this interface(the combination of SayHi and Sing).

Simply speaking, the interface defines a group of methods, if one object realize all methods of this interface, then this object realize this interface.

type Human struct {    name string    age int    phone string}type Student struct {    Human //匿名字段Human    school string    loan float32}type Employee struct {    Human //匿名字段Human    company string    money float32}//Human對象實現(xiàn)Sayhi方法func (h *Human) SayHi() {    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)}// Human對象實現(xiàn)Sing方法func (h *Human) Sing(lyrics string) {    fmt.Println("La la, la la la, la la la la la...", lyrics)}//Human對象實現(xiàn)Guzzle方法func (h *Human) Guzzle(beerStein string) {    fmt.Println("Guzzle Guzzle Guzzle...", beerStein)}// Employee重載Human的Sayhi方法func (e *Employee) SayHi() {    fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,        e.company, e.phone) //此句可以分成多行}//Student實現(xiàn)BorrowMoney方法func (s *Student) BorrowMoney(amount float32) {    s.loan += amount // (again and again and...)}//Employee實現(xiàn)SpendSalary方法func (e *Employee) SpendSalary(amount float32) {    e.money -= amount // More vodka please!!! Get me through the day!}// 定義interfacetype Men interface {    SayHi()    Sing(lyrics string)    Guzzle(beerStein string)}type YoungChap interface {    SayHi()    Sing(song string)    BorrowMoney(amount float32)}type ElderlyGent interface {    SayHi()    Sing(song string)    SpendSalary(amount float32)}

Men interface could be realized by Human, Student and Employee, one interface could be realizedd by a number of structs. Similarily, one struct could also realize more than one interface, Student realizes Men and YoungChap.

All types realize empty interface(without method):

interface{}        //empty interface

fmt.Println()

An constantly used output function, all types could be used as input which will be output as its initial form.

Here is how it is realized in the souce code:

type Stringer interface(){    String() string}

String is the pre-defined interface object, String() is a method whose return type is string, which means all types which could realize String() method can be disposed as the input and thus call fmt.Pringln().

So, if our struct could realize the so-called String() method, then our struct could also be compatible with fmt.Println().

package mainimport (    "fmt"    "strconv")type Human struct {    name string    age int    phone string}// 通過這個方法 Human 實現(xiàn)了 fmt.Stringerfunc (h Human) String() string {    return "?"+h.name+" - "+strconv.Itoa(h.age)+" years -  ? " +h.phone+"?"}func main() {    Bob := Human{"Bob", 39, "000-7777-XXX"}    fmt.Println("This Human is : ", Bob)}

Here our manully defined struct Human overloaded the method String(), so when we call the fmt.Println(), the customized output could be surpported.

The value of interface

So, what should we put into one interface? if we define a variable of interface, then this variable could store any object which has realized this interface.For the example above, if we define a variable m,then m can sore Human,Student,Employee.

package mainimport "fmt"type Human struct{    name string    age int    phone string}type Student struct{    Human    age int    phone string}type Employee struct{    Human    //anaonymous segment    company    loan float32}func (h Human)SayHi(){    fmt.Println("I am a human")}func (s Student)SayHi(){    fmt.Println("I am a studnet")}func (e Employee)SayHi(){    fmt.Println("I am a employee")}type Men interface{    SayHi()}func main(){    mike := Student{Human{"Mike",25,"222-222"},"MIT",0}    same := Employee{Human{"Sam",36,"333-333"},"Golang Inc.",1000}    var i Men    //defien a interface    i = mike    //i can store student    i.SayHi()    i = tom    i.SayHi()}

Empty interface

All types realized the empty interface.

var a interface{}var i int = 5s := "Hello world"http://a can store any typesa = ia = s

Comma-ok mechanisim(a little confusing)

We can overload the specific function for one type so as to make it suitable for some interfaces, but how can we know which kinds of type can realize a specific interface?

To judge a parameter's type, here is a syntax for this:

value, ok = element.(T)

element is the interface , T is the type which we want to know whether it corresponds to element,

Interface insertion

Interface1 could be a insertion of interface2 so that we do not have to write the same interfaces again and again.

type Interface interface {    sort.Interface //嵌入字段sort.Interface    Push(x interface{}) //a Push method to push elements into the heap    Pop() interface{} //a Pop elements that pops elements from the heap}

Interface could include all the interface of sort:

type Interface interface {    // Len is the number of elements in the collection.    Len() int    // Less returns whether the element with index i should sort    // before the element with index j.    Less(i, j int) bool    // Swap swaps the elements with indexes i and j.    Swap(i, j int)}

An other example of interface is:

// io.ReadWritertype ReadWriter interface {    Reader    Writer}

ReadWrite interface is simply the superposition of interface Reader and Write.

Reflection

1.get the reflect type of i first

t := reflect.TypeOf(i)    //得到類型的元數(shù)據(jù),通過t我們能獲取類型定義里面的所有元素v := reflect.ValueOf(i)   //得到實際的值牵咙,通過v我們獲取存儲在里面的值嵌洼,還可以去改變值
  1. get the corresponding value
tag := t.Elem().Field(0).Tag  //獲取定義在struct里面的標(biāo)簽name := v.Elem().Field(0).String()  //獲取存儲在第一個字段里面的值
  1. get the type and value of i
var x float64 = 3.4v := reflect.ValueOf(x)fmt.Println("type:", v.Type())fmt.Println("kind is float64:", v.Kind() == reflect.Float64)fmt.Println("value:", v.Float())

Here is the result:

type: float64kind is float64: truevalue: 3.4

If you execute the following code:

v.SetFloat(7.1)

the program will report a mestery error:

panic: reflect: reflect.Value.SetInt using unaddressable value

Here when we set the value of v, the passed input x is the copy of the original one, changing it is meaningless and illegal, this is the meaning of "unaddressable".

Similarly, passing the point of x is OK if you intend to change the value of x

var x float64 = 3.4p := reflect.ValueOf(&x)v := p.Elem()v.SetFloat(7.1)

Changing the address of x so as to change the value of it is workable.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子疟位,更是在濱河造成了極大的恐慌,老刑警劉巖硼补,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件茶鹃,死亡現(xiàn)場離奇詭異,居然都是意外死亡全释,警方通過查閱死者的電腦和手機(jī)装处,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來浸船,“玉大人妄迁,你說我怎么就攤上這事±蠲” “怎么了登淘?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長封字。 經(jīng)常有香客問我黔州,道長,這世上最難降的妖魔是什么阔籽? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任辩撑,我火速辦了婚禮,結(jié)果婚禮上仿耽,老公的妹妹穿的比我還像新娘合冀。我一直安慰自己,他們只是感情好项贺,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布君躺。 她就那樣靜靜地躺著峭判,像睡著了一般。 火紅的嫁衣襯著肌膚如雪棕叫。 梳的紋絲不亂的頭發(fā)上林螃,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機(jī)與錄音俺泣,去河邊找鬼疗认。 笑死,一個胖子當(dāng)著我的面吹牛伏钠,可吹牛的內(nèi)容都是我干的横漏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼熟掂,長吁一口氣:“原來是場噩夢啊……” “哼缎浇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起赴肚,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤素跺,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后誉券,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體指厌,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年踊跟,在試婚紗的時候發(fā)現(xiàn)自己被綠了仑乌。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡琴锭,死狀恐怖晰甚,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情决帖,我是刑警寧澤厕九,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站地回,受9級特大地震影響扁远,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜刻像,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一畅买、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧细睡,春花似錦谷羞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽犀填。三九已至,卻和暖如春嗓违,著一層夾襖步出監(jiān)牢的瞬間九巡,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工蹂季, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留冕广,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓偿洁,卻偏偏與公主長得像撒汉,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子父能,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,331評論 0 10
  • 不得不說地產(chǎn)這個行業(yè),不出幾本白皮書都不好意思說自己是混地產(chǎn)圈的净神。最流行的白皮書何吝,《+的進(jìn)化》世茂璀璨系,產(chǎn)品價值...
    郝志陽閱讀 440評論 0 0
  • 第一題的答案是在時間的情況下10+6=4鹃唯,也就是加上單位爱榕,10點鐘+6點鐘等于16點鐘,也就是下午4點鐘啊...
    vicky_維琪閱讀 2,732評論 0 1
  • 慢工出細(xì)活坡慌,不急于求成黔酥,精心制作,才能做出完美的產(chǎn)品『殚伲現(xiàn)代人的生活節(jié)奏越來越快跪者,許多事都求“多快好省”,而...
    上高湖李老師閱讀 152評論 0 0