-
-
Save knzm/1342411f980969c993414a8ae19ac92f to your computer and use it in GitHub Desktop.
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" | |
) | |
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