Menu

1 / 2

Go's cmp.Or and cmp.Compare: Three-Way Comparison Without the Boilerplate

DEV Community·Gabriel Anhaia·6 months ago
#eIfvUDqb
#pattern#go#programming#stdlib#compare
Reading 0:00
15s threshold

Book: The Complete Guide to Go Programming

Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go

My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools

Me: xgabriel.com | GitHub

Open the config loader of any Go service older than two years. You'll find this:

port := os . Getenv ( "APP_PORT" ) if port == "" { port = cfg . Port } if port == "" { port = "8080" }

Enter fullscreen mode

Exit fullscreen mode

Or this, on the sort path:

sort . Slice ( orders , func ( i , j int ) bool { if orders [ i ] . CreatedAt . Equal ( orders [ j ] . CreatedAt ) { return orders [ i ] . ID < orders [ j ] . ID } return orders [ i ] . CreatedAt . After ( orders [ j ] . CreatedAt ) })

Enter fullscreen mode

Exit fullscreen mode

Both shapes work. Both are the kind of thing a code reviewer skims past because the alternative used to be worse. Then Go 1.21 shipped the cmp package with cmp.Compare and cmp.Less .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.