golang 结构体中的匿名接口

golang 结构体中的匿名接口,第1张

概述golang 结构体中的匿名接口 代码示例 golang 中,可以给结构体增加匿名field,可参考 unknwon 大神的书。 匿名字段和内嵌结构体 但,golang同时也可以给结构体定义一个匿名interface field,用法: 标准库 sort 中,有下面的写法: type Interface interface { Len() int Less(i, j int) bo 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}}

reverse结构体内嵌了一个Interface的interface,并且,提供了单独的Less函数定义。
却没有提供 Len,Swap 的定义。

首先,根据结构体内嵌其它匿名字段的定义,可以推知,理论上,调用reverse.Len,reverse.Swap
肯定是会直接传递到 reverse.Interface.Lenreverse.Interface.Swap
即,和直接调用Interface的同名函数没有任何区别。

但,reverse提供了单独的Less函数,它的实现是颠倒了i,j参数,仍然送入到Interface.Less中去,
那么,得出的结果与直接使用Interface排序的结果,肯定是相反的。

为什么如此设计?

Meaning of a struct with embedded anonymous interface?

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

In this way reverse implements the sort.Interface and we can overrIDe a specific method without having to define all the others. 结构体创建时,可以使用任何实现了Interface的obj来初始化,参考:
package mainimport "fmt"// some interfacetype Stringer interface {    String() string}// a struct that implements Stringer interfacetype Struct1 struct {    fIEld1 string}func (s Struct1) String() string {    return s.fIEld1}// another struct that implements Stringer interface,but has a different set of fIEldstype 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 interfacetype 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"})}
总结

以上是内存溢出为你收集整理的golang 结构体中的匿名接口全部内容,希望文章能够帮你解决golang 结构体中的匿名接口所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1270474.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存