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对象实现Sayhi方法func (h *Human) SayHi() {    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)}// Human对象实现Sing方法func (h *Human) Sing(lyrics string) {    fmt.Println("La la, la la la, la la la la la...", lyrics)}//Human对象实现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实现BorrowMoney方法func (s *Student) BorrowMoney(amount float32) {    s.loan += amount // (again and again and...)}//Employee实现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 实现了 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"//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)    //得到类型的元数据,通过t我们能获取类型定义里面的所有元素v := reflect.ValueOf(i)   //得到实际的值,通过v我们获取存储在里面的值,还可以去改变值
  1. get the corresponding value
tag := t.Elem().Field(0).Tag  //获取定义在struct里面的标签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.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,001评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,210评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,874评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,001评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,022评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,005评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,929评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,742评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,193评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,427评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,583评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,305评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,911评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,564评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,731评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,581评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,478评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,322评论 0 10
  • 不得不说地产这个行业,不出几本白皮书都不好意思说自己是混地产圈的。最流行的白皮书,《+的进化》世茂璀璨系,产品价值...
    郝志阳阅读 438评论 0 0
  • 第一题的答案是在时间的情况下10+6=4,也就是加上单位,10点钟+6点钟等于16点钟,也就是下午4点钟啊...
    vicky_维琪阅读 2,722评论 0 1
  • 慢工出细活,不急于求成,精心制作,才能做出完美的产品。现代人的生活节奏越来越快,许多事都求“多快好省”,而...
    上高湖李老师阅读 151评论 0 0