Created
January 10, 2015 16:25
-
-
Save SteveBate/4f88644943d6f1eb0c18 to your computer and use it in GitHub Desktop.
Example of sorting a map via different sorting implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
type Person struct { | |
Title string | |
FirstName string | |
LastName string | |
Address | |
} | |
type Address struct { | |
HouseNumber int | |
Street string | |
Town string | |
PostCode string | |
} | |
// different sort implementations | |
type BySurname map[int]Person | |
func (b BySurname) Len() int { return len(b) } | |
func (b BySurname) Swap(i, j int) { b[i], b[j] = b[j], b[i] } | |
func (b BySurname) Less(i, j int) bool { return b[i].LastName < b[j].LastName } | |
type ByHouseNumber map[int]Person | |
func (b ByHouseNumber) Len() int { return len(b) } | |
func (b ByHouseNumber) Swap(i, j int) { b[i], b[j] = b[j], b[i] } | |
func (b ByHouseNumber) Less(i, j int) bool { return b[i].HouseNumber < b[j].HouseNumber } | |
type ByStreet map[int]Person | |
func (b ByStreet) Len() int { return len(b) } | |
func (b ByStreet) Swap(i, j int) { b[i], b[j] = b[j], b[i] } | |
func (b ByStreet) Less(i, j int) bool { return b[i].Street < b[j].Street } | |
func main() { | |
people := map[int]Person{ | |
0: Person{"Mr", "Joe", "Bloggs", Address{30, "Rose Lea", "Preston", "PR2 9LA"}}, | |
1: Person{"Mr", "John", "Smith", Address{6, "Samuel Street", "Preston", "PR1 4YJ"}}, | |
2: Person{"Mr", "Dave", "Jones", Address{54, "St. Vincents Road", "Preston", "PR3 14Y"}}, | |
} | |
sort.Sort(ByHouseNumber(people)) // or sort.Sort(BySurname(people)) or sort.Sort(ByStreet(people)) | |
// iterate over the map with a traditional for loop - don't user (for i, _ := range) as return order is randomised | |
for i := 0; i < len(people); i++ { | |
fmt.Printf("%s %s %s, %d, %s, %s, %s\n", | |
people[i].Title, | |
people[i].FirstName, | |
people[i].LastName, | |
people[i].HouseNumber, | |
people[i].Street, | |
people[i].Town, | |
people[i].PostCode) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment