Go · Level 2 Generics

Type Constraints

Write a Number constraint and a generic Sum in Go that works for int, float64 and named types like Cents, using ~int so types built on int are accepted too.

  • a constraint lists allowed types
  • int | float64 is a union
  • ~int also accepts type Cents int

A constraint is an interface listing allowed types, like int | float64. Trap: int accepts only int itself, not type Cents int; write ~int to accept every type built on int.

type Cents int
type Exact interface{ int }   // not Cents
type Built interface{ ~int }  // Cents too

Write a Number constraint and Sum[T Number](xs []T) T that adds up a slice of ints, float64s, or types built on them like Cents. Example: Sum([]Cents{120, 80}) → 200.

solution.go
Test Suites Pending
Output