sort
个套餐:
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
...
type reverse struct {
Interface
}
struct reverse
中匿名接口Interface
的含义是什么?
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}
}
如果您想一想,如果这种方法不可能,您将不得不做什么,那么真正的价值就来了.
sort.Interface
上再加Reverse
个方法?所有这些更改都需要跨越数千个想要使用标准反向功能的包的更多代码行.