doufu1939 2014-07-02 17:30
浏览 40
已采纳

具有嵌入式匿名接口的结构的含义?

sort package:

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

...

type reverse struct {
    Interface
}

What is the meaning of anonymous interface Interface in struct reverse?

  • 写回答

4条回答 默认 最新

  • dsdvr06648 2014-07-02 18:00
    关注

    In this way reverse implements the sort.Interface and we can override a specific method without having to define all the others

    type reverse struct {
            // This embedded Interface permits Reverse to use the methods of
            // another Interface implementation.
            Interface
    }
    

    Notice how here it swaps (j,i) instead of (i,j) and also this is the only method declared for the struct reverse even if reverse implement sort.Interface

    // Less returns the opposite of the embedded implementation's Less method.
    func (r reverse) Less(i, j int) bool {
            return r.Interface.Less(j, i)
    }
    

    Whatever struct is passed inside this method we convert it to a new reverse struct.

    // Reverse returns the reverse order for data.
    func Reverse(data Interface) Interface {
            return &reverse{data}
    }
    

    The real value comes if you think what would you have to do if this approach was not possible.

    1. Add another Reverse method to the sort.Interface ?
    2. Create another ReverseInterface ?
    3. ... ?

    Any of this change would require many many more lines of code across thousands of packages that want to use the standard reverse functionality.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题