Sorting:
var p []Person sort.Sort(byName(p)) sort.Sort(byAge(p)) sort.Sort(bySSN(p)) type byName []Person func (b byName) Len() int { return len(b) } func (b byName) Less(i, j int) bool { return b[i].Name < b[j].Name } func (b byName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } type byAge []Person func (b byAge) Len() int { return len(b) } func (b byAge) Less(i, j int) bool { return b[i].AgeYears < b[j].AgeYears } func (b byAge) Swap(i, j int) { b[i], b[j] = b[j], b[i] } type bySSN []Person func (b bySSN) Len() int { return len(b) } func (b bySSN) Less(i, j int) bool { return b[i].SSN < b[j].SSN } func (b bySSN) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
Tedious, thus:
https://golang.org/pkg/sort/#Slice
https://golang.org/pkg/sort/#SliceStable
https://golang.org/pkg/sort/#SliceIsSorted
sort.Slice(p, func(i, j int) bool { return p[i].Name < p[j].Name }) sort.Slice(p, func(i, j int) bool { return p[i].AgeYears < p[j].AgeYears }) sort.Slice(p, func(i, j int) bool { return p[i].SSN < p[j].SSN })
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.