import(
"fmt"
"sort"
"math/rand"
)
const(
male = iota
female
unknown
)
var genderStr []string=[]string{"male","female","unknown",}
type People struct{
Id int `ID`
Age int `Age`
Name string `Name`
Gender int `Gender`
}
func (p People) String() string{
return fmt.Sprintf("People %q of age %v with ID %v,Gender %s\n",p.Name,p.Age,p.Id,genderStr[p.Gender])
}
type Classmate []People
func (c Classmate) Len() int { return len(c) }
func (c Classmate) Less(i,j int) bool { return c[i].Age<c[j].Age }
func (c Classmate) Swap(i,j int) { c[i],c[j]=c[j],c[i] }
func main(){
cs:=make (Classmate,10,20)
for i:=0;i<len(cs); i++ {
cs[i].Id=i
cs[i].Age=rand.Intn(50)
cs[i].Name=fmt.Sprintf("cs_%v",i)
cs[i].Gender=rand.Intn(3)
}
fmt.Println(cs)
sort.Sort(cs)
fmt.Println(cs)
}
Screen output sample:
[People "cs_0" of age 31 with ID 0,Gender male
People "cs_1" of age 47 with ID 1,Gender unknown
People "cs_2" of age 31 with ID 2,Gender male
People "cs_3" of age 25 with ID 3,Gender unknown
People "cs_4" of age 6 with ID 4,Gender male
People "cs_5" of age 44 with ID 5,Gender female
People "cs_6" of age 12 with ID 6,Gender unknown
People "cs_7" of age 28 with ID 7,Gender unknown
People "cs_8" of age 11 with ID 8,Gender unknown
People "cs_9" of age 37 with ID 9,Gender unknown
]
[People "cs_4" of age 6 with ID 4,Gender male
People "cs_8" of age 11 with ID 8,Gender unknown
People "cs_6" of age 12 with ID 6,Gender unknown
People "cs_3" of age 25 with ID 3,Gender unknown
People "cs_7" of age 28 with ID 7,Gender unknown
People "cs_0" of age 31 with ID 0,Gender male
People "cs_2" of age 31 with ID 2,Gender male
People "cs_9" of age 37 with ID 9,Gender unknown
People "cs_5" of age 44 with ID 5,Gender female
People "cs_1" of age 47 with ID 1,Gender unknown
有疑问加站长微信联系(非本文作者)