DiagnosticsError codes
M0026 type argument does not satisfy constraint
A generic function or type was instantiated with a type argument outside the type set of its constraint.
example $ marmot build . error[M0026]: float32 does not satisfy Number (float32 missing in ~int | ~float64) --> ./main.go:14:6 | 3 | type Number interface{ ~int | ~float64 } | ------ `Number` is declared here ... 14 | _ = Sum([]float32{1}) | ^^^ ------------ the type argument is inferred as `float32` from this | | | `float32` does not satisfy `Number` | = note: the type set of `Number` is `~int | ~float64` = help: use a type in the set, for example `float64` instead of `float32` error: build failed with 1 error for more about an error, run `marmot explain M0026`
The program that produced it
package main
type Number interface{ ~int | ~float64 }
func Sum[T Number](xs []T) T {
var s T
for _, x := range xs {
s += x
}
return s
}
func main() {
_ = Sum([]float32{1})
}
For a ~T term, the underlying type of the argument must be T.
The mistake and the fix
type Number interface{ ~int | ~float64 }
func Sum[T Number](xs []T) T
Sum([]float32{1})type Number interface{ ~int | ~float32 | ~float64 }
func Sum[T Number](xs []T) T
Sum([]float32{1})The fix
Use a type in the set, or widen the constraint.
See also all error codes and marmot explain.