Golang uses a composite to extend and override functions. Golang uses a composite to extend and override functions. Have you ever seen anonymous interface written in struct?

This Interface is used as an anonymous field in a struct, and is written as such in the library’s sort package:

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

type reverse struct {
    Interface
}Copy the code

Let’s look at a complete example. The following code is extracted from the sort package:

package main import ( "fmt" ) type Interface interface { Len() int Less(i, j int) bool Swap(i, Type Array []int func (arr Array) Len() int {return Len(arr)} func (arr Array) Less(I,  j int) bool { return arr[i] < arr[j] } func (arr Array) Swap(i, j int) { arr[i], arr[j] = arr[j], Arr [I]} // override func (r reverse) Less(I, j int) bool { return r.Interface.Less(j, Func reverse (data Interface) Interface {return &reverse{data}} func main() {arr := Array{1, 2, 3} rarr := Reverse(arr.Less(0,1)) Println(arr.Less(0,1))}Copy the code

The purpose of the sort package is to override the Less method of the Interface and make use of the original Less method. Reverse can be used to construct a Reverse Interface from an Interface. The GO language takes advantage of composition and rewrites in a few lines of code.

The advantages of the anonymous interface can be better understood by comparing the traditional combination of anonymous structure implementation rewrite:

package main import ( "fmt" ) type Interface interface { Len() int Less(i, j int) bool Swap(i, j int) } type Array []int func (arr Array) Len() int { return len(arr) } func (arr Array) Less(i, j int) bool { return arr[i] < arr[j] } func (arr Array) Swap(i, j int) { arr[i], arr[j] = arr[j], Arr [I]} // anonymous struct type reverse struct {Array} // rewrite func (r reverse) Less(I, j int) bool {return r.array.less (j, j int) Func (data Array) Interface {return &reverse{data}} func main() {arr := Array{1, 2, 3} rarr := Reverse(arr) fmt.Println(arr.Less(0, 1)) fmt.Println(rarr.Less(0, 1)) }Copy the code

The above example uses an anonymous structure that implements the same override functionality as, or very similar to, the previous anonymous interface. However, if you look closely, you will see the advantages of anonymous interfaces, which are implementation-independent and can be overridden by any type that implements the interface. This is very useful when writing public libraries, and if you have looked at the source code of some libraries often, the anonymous interface should look familiar.