sort个套餐:

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

...

type reverse struct {
    Interface
}

struct reverse中匿名接口Interface的含义是什么?

推荐答案

通过这种方式,reverse实现了sort.Interface,我们可以覆盖一个特定的方法

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

注意这里它是如何交换(j,i)而不是(i,j)的,而且这是为 struct reverse声明的唯一方法,即使reverse实现了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)
}

无论此方法内部传递的是什么 struct ,我们都会将其转换为新的reverse struct .

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

如果您想一想,如果这种方法不可能,您将不得不做什么,那么真正的价值就来了.

  1. sort.Interface上再加Reverse个方法?
  2. 是否创建另一个ReverseInterface?
  3. .?

所有这些更改都需要跨越数千个想要使用标准反向功能的包的更多代码行.

Go相关问答推荐

如何从google.golang.org/grpc/stats包中将golang中不同事件的输出进行组合,以获取func HandlePRC

你能帮我优化一个golang代码关于函数CrossPointTwoRect

Pulumi-S3-当策略依赖于访问点时,如何将AccesspintPolicy附加到访问点

golang 的通用 map 功能

困扰围棋官方巡回赛的S建议所有方法都使用同一类型的接收器

GO错误:Tim.Time未实现driver.Valuer(缺少方法值)

Docker Compose Health Check未退出,错误为无法启动

Golang内置打印(Ln)函数&S行为怪异

Azure golang SDK - 将 AcrPull 角色分配给 AKS 群集

使用 Golang 获取目录磁盘使用情况

如何忽略打印达到最大深度限制 go colly

io.Reader 无限循环与 fmt.Fscan

无法使用带有 422 的 go-github 创建提交 - 更新不是快进

如何从 Asterisk Manager Interface Event 获取活动呼叫数

设置 graphql 的最大文件上传大小(golang)

errors.Wrap 和 errors.WithMessage 有什么区别

设置指向空接口的指针

如何仅提取时间作为持续时间

Go 赋值涉及到自定义类型的指针

Gin中测试模式有什么用