Search code examples
goencapsulation

Encapsulating `sort` Interface in Golang


I am trying to sort a slice of structs in Go. I can implement the sort.Interface by defining 3 methods at the top level of the package:

type byName []*Foo // struct Foo is defined in another package

func (a byName) Len() int           { return len(a) }
func (a byName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }

func Bar() {
    var foos []*Foo // Populated by a call to an outside function

    sort.Sort(byName(foos))
    ...
}

Is there any way to move the 3 method definitions (Len, Swap, and Less) into the Bar function, defining an anonymous method in Go?

// Something like this
func Bar() {
    ...
    Len := func (a byName)() int { return len(a) }
}

Can the 3 methods defined at the top level be accessed from outside of this package? I am guessing not, because the type byName is local.


Solution

  • Simple answer, no, there are no such things as anonymous methods in Go.

    As anonymous functions cannot be declared using a receiver, they are effectively not methods, therefore the byName type would not implement the required sort.Interface.