Generics and the standard library
Type parameters, constraints, and knowing what is already written for you.
What does ~int mean in a constraint?
All questions with explanations (answers shown)
1. What does
~intmean in a constraint?Answer: Any type whose underlying type is int, so
type UserID intqualifiesWithout the tilde, only
intitself satisfies it — your own named types would not.2. When is an interface the right tool instead of a generic?
Answer: When the operation is about what a type does, not what it is
Generics parameterise over types; interfaces abstract over behaviour.
Shapeis an interface.Sum[T Number]is a generic.3. Which package should you use for random values in a security token?
Answer:
crypto/randmath/randis not cryptographically secure: its output can be predicted from earlier outputs, or reproduced outright if it was seeded with something guessable like the time. For tokens that is a real vulnerability, not a nitpick.4. When should you reach for generics?
Answer: After you have written the concrete version two or three times
Premature generics make code harder to read and often guess the wrong abstraction. Check
slicesandmapsfirst: much of what people hand-roll is already there.5. Which of these compiles?
Answer:
func Max[T cmp.Ordered](a, b T) T { if a > b { return a }; return b }>needs an ordered type.anyallows every type, andcomparableonly guarantees==and!=, so both are rejected.cmp.Orderedis the constraint for<and>. (For two values, the built-inmaxalready exists.)6.
type Celsius float64. Which constraint letsSum[T]accept a[]Celsius?Answer:
interface{ ~float64 }~float64means "any type whose underlying type is float64", which includesCelsius. Plainfloat64matches onlyfloat64itself.anywould acceptCelsiusbut would not allow+in the body.7. What does
for i := range 3 { fmt.Print(i) }print in Go 1.22+?Answer:
012Since Go 1.22 you can range over an integer
n, which yields0up ton-1. It is the short form offor i := 0; i < 3; i++.