If Go’s interfaces aren’t enforced, are they necessary?

Yes. Go doesn’t allow you to build type-hierarchies, so interfaces are very important to allow some polymorphism. Consider the sort.Interface defined in the package 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)
}

The sort package contains a function sort(data Interface) that expects any object that implements this interface. Without interfaces, such form of polymorphism would not be possible in go. The fact that you don’t have to explicitly annotate that your type implements this interface, is irrelevant.

The cool part about go is that you can even implement this interface on primitive types, as long as the type is defined in the same package. So the following code defines a sortable array of integers:

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]
}

Leave a Comment