How to sort them by LastName and then by FirstName

Go:
1
2
3
4
5
6
7
type Member struct {
    Id int
    LastName string
    FirstName string
}

var members []Member

The less function is specified using an anonymous function with sort.Slice:

Go:
1
2
3
4
5
6
7
var members []Member
sort.Slice(members, func(i, j int) bool {
    if members[i].LastName != members[j].LastName {
        return members[i].LastName < members[j].LastName
    }
    return members[i].FirstName < members[j].FirstName
})

Or less with switch:

Go:
1
2
3
4
5
6
7
8
9
sort.Slice(members, func(i, j int) bool {
    switch strings.Compare(members[i].FirstName, members[j].FirstName) {
    case -1:
        return true
    case 1:
        return false
    }
    return members[i].LastName > members[j].LastName
})

See more:

Go:
1
2
3
4
5
type TheStruct struct {
	Generation int
	Time       int
	Version    int
}

We want to sort it in ascending order after Version, Generation and Time.

Go:
1
2
3
4
5
6
7
8
9
10
11
sort.Slice(structs, func(i, j int) bool {
	iv, jv := structs[i], structs[j]
	switch {
	case iv.Version != jv.Version:
		return iv.Version < jv.Version
	case iv.Generation != jv.Generation:
		return iv.Generation < jv.Generation
	default:
		return iv.Time < jv.Time
	}
})