golang 结构体中的匿名接口
golang 结构体中的匿名接口代码示例golang 中,可以给结构体增加匿名field,可参考 unknwon 大神的书。 匿名字段和内嵌结构体 但,golang同时也可以给结构体定义一个匿名interface field,用法: 标准库 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} } reverse结构体内嵌了一个 首先,根据结构体内嵌其它匿名字段的定义,可以推知,理论上,调用 但, 为什么如此设计?Meaning of a struct with embedded anonymous interface? 摘录其中比较关键的解释如下:
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"}) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |