具有嵌入式匿名接口的结构的含义? [英] Meaning of a struct with embedded anonymous interface?
问题描述
sort
包:
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
...
type reverse struct {
Interface
}
struct reverse
中的匿名接口Interface
是什么意思?
What is the meaning of anonymous interface Interface
in struct reverse
?
推荐答案
这样反向实现了 sort.Interface
并且我们可以重写一个特定的方法无需定义所有其他
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
}
注意这里如何交换 (j,i)
而不是 (i,j)
并且这是为结构 reverse<声明的唯一方法/code> 即使
reverse
实现 sort.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)
}
无论在此方法中传递什么结构,我们都会将其转换为新的 reverse
结构.
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.
- 在
sort.Interface
中添加另一个Reverse
方法? - 创建另一个反向接口?
- ... ?
- Add another
Reverse
method to thesort.Interface
? - Create another ReverseInterface ?
- ... ?
任何这种更改都需要在数千个想要使用标准反向功能的包中编写更多行代码.
Any of this change would require many many more lines of code across thousands of packages that want to use the standard reverse functionality.
这篇关于具有嵌入式匿名接口的结构的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!