golang 结构体中的匿名接口

代码示例

golang 中,可以给结构体增加匿名field,可参考 unknwon 大神的书。

但,golang同时也可以给结构体定义一个匿名interface field,用法:

sort
type interfacE interface {
    Len() int
    Less(i,j int) bool
    Swap(i,j int)
}

type reverse struct {
    Interface
}

func (r reversE) Less(i,j int) bool {
    return r.Interface.Less(j,i)
}

func Reverse(data InterfacE) Interface {
    return &reverse{data}
}
InterfaceLessLenSwap
reverse.Lenreverse.Swapreverse.Interface.Lenreverse.Interface.Swap
reverseLessi,jInterface.Less

为什么如此设计?

摘录其中比较关键的解释如下:

reversesort.InterfaceInterface
package main

import "fmt"

// somE interface
type Stringer interface {
    String() String
}

// a struct that implements Stringer interface
type Struct1 struct {
    field1 String
}

func (s Struct1) String() String {
    return s.field1
}


// another struct that implements Stringer interface,but has a different set of fields
type Struct2 struct {
    field1 []String
    dummy bool
}

func (s Struct2) String() String {
    return fmt.Sprintf("%v,%v",s.field1,s.dummy)
}


// container that can embedd any struct which implements Stringer interface
type StringerContainer struct {
    Stringer
}


func main() {
    // the following prints: This is Struct1
    fmt.Println(StringerContainer{Struct1{"This is Struct1"}})
    // the following prints: [This is Struct1],true
    fmt.Println(StringerContainer{Struct2{[]String{"This","is","Struct1"},truE}})
    // the following does not compile:
    // cAnnot use "This is a type that does not implement Stringer" (type String)
    // as type Stringer in field value:
    // String does not implement Stringer (missing String method)
    fmt.Println(StringerContainer{"This is a type that does not implement Stringer"})
}