我实现了一个界面几何,并有一部分[]几何,
anything := []geometry{
rect{width: 3, height: 4, name: "rect"},
circle{radius: 5, name: "circle"},
}
现在我要按名称对切片进行排序,更改切片中元素的顺序。我可以使用getName函数来获取名称。排序后,我希望它像片一样
{circle{radius: 5, name: "circle"},rect{width: 3, height: 4, name: "rect"},}
这是代码
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())
}
}
答案 0 :(得分:3)
对于sort.Slice(...)
来说,这是一项简单的任务,与此处的示例非常相似!
您需要做的就是用您的“ anything”切片和一个“ Less”函数调用该函数,该函数比较anything[x].getName()
的结果。
例如(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.