I implemented an interface geometry and have a slice of it []geometry,
anything := []geometry{
rect{width: 3, height: 4, name: "rect"},
circle{radius: 5, name: "circle"},
}
now I want to sort the slice by name, change the sequence of elements in the slice. I can use getName function to get the name. After sorting, I want it like a slice like
{circle{radius: 5, name: "circle"},rect{width: 3, height: 4, name: "rect"},}
Here is the code
package main
import (
"fmt"
"math"
"sort"
)
type geometry interface {
area() float64
perim() float64
getName() string
}
type rect struct {
width, height float64
name string
}
type circle struct {
radius float64
name string
}
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (r rect) getName() string {
return r.name
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func (c circle) getName() string {
return c.name
}
func main() {
anything := []geometry{
rect{width: 3, height: 4, name: "rect"},
circle{radius: 5, name: "circle"},
}
for i := range anything {
fmt.Println(anything[i].getName())
}
}
This is an easy task for sort.Slice(...)
and is very similar to the example there!
All you need to do is call that function with your "anything" slice and a "Less" function which compares the result of anything[x].getName()
.
For example (Go Playground):
sort.Slice(anything, func(i, j int) bool {
return anything[i].getName() < anything[j].getName()
})
// Now the items in "anything" are sorted alphabetically by name.