我試圖有兩種變體的排序方法:一種按名稱排序元素的形式,另一種按薪水排序元素。 sort.Sort(人(數據))工作時,我較少的方法比較whatever.salary。如果我將其更改爲whatever.name,它也可以工作。我希望能夠在less方法中具體調用這兩個選項,如下面的代碼所示。我的邏輯是使用sort.Sort(people(data.name))作爲名字,sort.Sort(people(data.salary))作爲薪水。這些都不起作用。這甚至可以完成?在Go中,當使用多個返回語句時,如何調用每個特定的語句?
package main
import (
"fmt"
"sort"
)
type Comparable interface {
Len()
Less(i, j int) bool
Swap(i, j int)
}
type person struct {
name string
salary float64
}
func (a person) String() string {
return fmt.Sprintf("%s: %g \n", a.name, a.salary)
}
type people []*person
func (a people) Len() int {
return len(a)
}
func (a people) Less(i, j int) bool {
return a[i].salary < a[j].salary
return a[i].name < a[j].name
}
func (a people) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func main() {
var data = make(people, 10)
var a, b, c, d, e, f, g, h, i, j person
a.name, b.name, c.name, d.name, e.name, f.name,
g.name, h.name, i.name, j.name = "Sheila Broflovski", "Ben Affleck",
"Mr. Hankey", "Stan Marsh", "Kyle Broflovski", "Eric Cartman",
"Kenny McCormick", "Mr. Garrison", "Matt Stone", "Trey Parker"
a.salary, b.salary, c.salary, d.salary, e.salary, f.salary,
g.salary, h.salary, i.salary, j.salary = 82000, 74000, 0, 400,
2500, 1000, 4, 34000, 234000, 234000
a.salary = 82000
data[0] = &a
data[1] = &b
data[2] = &c
data[3] = &d
data[4] = &e
data[5] = &f
data[6] = &g
data[7] = &h
data[8] = &i
data[9] = &j
fmt.Println("\n\n\n")
fmt.Print(data)
sort.Sort(people(data)) //This works even with the two return statements
sort.Sort(people(data.name)) //This does not work. Exist, a version that does?
sort.Sort(people(data.salary)) //This does not work. Exist, a version that does?
fmt.Println("\n\n\n")
fmt.Print(data)
}