如果没有强制执行Go的接口,它们是否必要?

Car*_*son 1 go

Go语言将接口类型作为功能,类似于C风格的接口.但是,Go的接口类型似乎没有被强制执行 - 它们只是定义协议而不实际应用于类型.由于它们没有强制执行,使用接口仍然是个好主意吗?

Eli*_*ing 7

是.Go不允许您构建类型层次结构,因此接口对于允许某些多态性非常重要.考虑sort.Interface包中定义的sort:

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less returns whether the element with index i should sort
    // before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}
Run Code Online (Sandbox Code Playgroud)

sort包包含一个函数sort(data Interface),该函数需要任何实现此接口的对象.如果没有接口,那么这种形式的多态性就无法实现.您不必显式注释您的类型实现此接口的事实是无关紧要的.

关于go的酷炫部分是你甚至可以在基本类型上实现这个接口,只要在同一个包中定义类型.因此,以下代码定义了一个可排序的整数数组:

type Sequence []int

// Methods required by sort.Interface.
func (s Sequence) Len() int {
    return len(s)
}
func (s Sequence) Less(i, j int) bool {
    return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
Run Code Online (Sandbox Code Playgroud)

  • "你甚至可以在基本类型上实现这个接口"你的意思是你可以定义自定义类型的方法,这些方法在结构上可能与基本类型相同.`Sequence`和`[] int`是不同的类型. (4认同)