由于 Go 使用组合系统而不是(多重)继承,我只是想知道这 3 个代码片段。 Go 说他们强制程序员使用组合。
A) 应该是(几乎)正确的 Go 代码, B)伪 C)伪
恕我直言,这三种代码的结果总是相同的,除此之外,B) 和 C) 可以用于更多的东西,而 A) 迫使你坚持组合?
即使您假设 B) 在类内部没有排序方法,但是 - 让我们说像 A) 这样的全局方法并没有真正的区别 oO
A) 代码:
interface Sort
Len()
Less(i, j int) bool
Swap(i, j int)
func (qs *Sort) sort()
doTheSorting
type MyData struct {
var value int
}
func (s *MyData) Len() { ... }
func (s *MyData) Less(i, j int) bool { ... }
func (s *MyData) Swap(i, j int) { ... }
B) 看起来像继承,但根据编译器的工作方式,恕我直言,可以将其视为嵌入式。
class Sort
public sort() { ... }
abstract Len()
abstract Less(i, j int) bool
abstract Swap(i, j int)
C)
interface SortInterface
void Len()
bool Less(i, j int)
void Swap(i, j int)
class Sort implements SortInterface
public sort() { ... }
用法 B 和 C:
class MyClass **embed** Sort
int value
void Len() { ... }
bool Less(i, j int) { ... }
void Swap(i, j int) { ... }
最佳答案
不,这不是 go 的工作方式。这是一个可以排序的类型的示例(从标准库中提取)。
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
这实现了接口(interface):
// Name of interface changed for clarity
type Sort interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
实现Sort
接口(interface)的类型没有新方法。您不能将方法分配给接口(interface),例如您的示例 func (qs *Sort) sort() {...}
。
但是,允许将其传递给需要Sort
类型变量的函数和方法。因此,我可以调用 sort.Sort(myIntSlice)
然后对其进行排序。
这是一个示例函数,它采用实现Sort
接口(interface)的任何参数:
func IsSorted(data Sort) bool {
n := data.Len()
for i := n - 1; i > 0; i-- {
if data.Less(i, i-1) {
return false
}
}
return true
}
在 IsSorted
中,函数不知道数据的真实类型是什么。它可以是 IntSlice
或其他任何东西。它所知道的是,无论您提供给它什么参数,它都会实现 Sort 接口(interface)中的方法。
但是我似乎无法弄清楚你问的问题。此外,伪代码很难理解。使用另一种语言(例如 java)会更好。
关于inheritance - 组合和多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11148299/