package main
import (
"fmt"
"sort"
)
// ------------------------------------------------------------
// Example: Sorting a slice of user-defined structs
// that contain nested structs
// ------------------------------------------------------------
// A nested struct representing an address
type Address struct {
City string
Zip int
}
// A struct representing a person, containing a nested Address
type Person struct {
Name string
Age int
Address Address
}
// ------------------------------------------------------------
// Helper function to print the list
// ------------------------------------------------------------
func printPersons(people []Person) {
for _, p := range people {
fmt.Printf("%s | age: %d | city: %s | zip: %d\n",
p.Name, p.Age, p.Address.City, p.Address.Zip)
}
}
func main() {
// Create a sample list of people
people := []Person{
{"Alice", 30, Address{"San Francisco", 42100}},
{"Bob", 40, Address{"Austin", 32000}},
{"Carol", 35, Address{"New York City", 42000}},
{"Dave", 25, Address{"Austin", 32000}},
{"Eve", 28, Address{"New York City", 61000}},
}
// ------------------------------------------------------------
// Sort using sort.Slice:
// 1. Compare by city
// 2. Then by zip
// 3. Then by age
// ------------------------------------------------------------
sort.Slice(people, func(i, j int) bool {
a, b := people[i], people[j]
if a.Address.City != b.Address.City {
return a.Address.City < b.Address.City
}
if a.Address.Zip != b.Address.Zip {
return a.Address.Zip < b.Address.Zip
}
return a.Age < b.Age
})
// Print the sorted result
printPersons(people)
}
/*
run:
Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100
*/