Dev Skills
Go tests·7 questions

Generics and the standard library

Type parameters, constraints, and knowing what is already written for you.

1 / 7

What does ~int mean in a constraint?

All questions with explanations (answers shown)
  1. 1. What does ~int mean in a constraint?

    Answer: Any type whose underlying type is int, so type UserID int qualifies

    Without the tilde, only int itself satisfies it — your own named types would not.

  2. 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. Shape is an interface. Sum[T Number] is a generic.

  3. 3. Which package should you use for random values in a security token?

    Answer: crypto/rand

    math/rand is 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. 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 slices and maps first: much of what people hand-roll is already there.

  5. 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. any allows every type, and comparable only guarantees == and !=, so both are rejected. cmp.Ordered is the constraint for < and >. (For two values, the built-in max already exists.)

  6. 6. type Celsius float64. Which constraint lets Sum[T] accept a []Celsius?

    Answer: interface{ ~float64 }

    ~float64 means "any type whose underlying type is float64", which includes Celsius. Plain float64 matches only float64 itself. any would accept Celsius but would not allow + in the body.

  7. 7. What does for i := range 3 { fmt.Print(i) } print in Go 1.22+?

    Answer: 012

    Since Go 1.22 you can range over an integer n, which yields 0 up to n-1. It is the short form of for i := 0; i < 3; i++.