Menu

1 / 2

Generic Constraints in Go: comparable, ~int, and the Trap of Underlying Types

DEV Community·Gabriel Anhaia·7 months ago
#870NSbjV
#go#generics#programming#type#constraint
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

You write a tiny utility. A generic Min function. Two arguments, returns the smaller one. The first version uses any and the compiler rejects it because you cannot apply < to any . You switch to comparable and the compiler still rejects it, because comparable covers == and != , not ordering. You finally land on cmp.Ordered and ship it. Then a teammate asks why their custom Score type compiles fine, but Min cannot call .String() on the value inside its body.

That last part is where most Go developers learn that constraints describe a set of types, not a class of objects.…

Continue reading — create a free account

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