Skip to content

Instantly share code, notes, and snippets.

@knzm
Forked from podhmo/main.go
Last active August 2, 2018 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knzm/1342411f980969c993414a8ae19ac92f to your computer and use it in GitHub Desktop.
Save knzm/1342411f980969c993414a8ae19ac92f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sort"
)
func formatIntPtr(fmtstr, nilstr string, p *int) string {
if p == nil {
return nilstr
}
return fmt.Sprintf(fmtstr, *p)
}
func main() {
type P struct {
X *int
Y *int
}
Int := func(n int) *int {
return &n
}
xs := []P{
{X: Int(10), Y: Int(20)},
{X: Int(100), Y: Int(20)},
{X: Int(10), Y: Int(200)},
{X: Int(100), Y: Int(200)},
{X: nil, Y: Int(20)},
{X: nil, Y: Int(200)},
{X: Int(100), Y: nil},
{X: Int(10), Y: nil},
{X: nil, Y: nil},
}
cmp := func(pa, pb *int) int {
switch {
case pa == nil && pb == nil:
return 0
case pa == nil && pb != nil:
return 1
case pa != nil && pb == nil:
return -1
default:
return *pb - *pa
}
}
sort.Slice(xs, func(i, j int) bool {
n := cmp(xs[i].X, xs[j].X)
if n == 0 {
n = cmp(xs[i].Y, xs[j].Y)
}
return n >= 0
})
for _, x := range xs {
fmt.Printf(
"(%s, %s)\n",
formatIntPtr("%3d", "nil", x.X),
formatIntPtr("%3d", "nil", x.Y),
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment