go type constraint

tags: learning go programming

content

Note

Type constraint is to be used in generics, not as a real type!!
type constraint says: “this generic function accepts any types that are constrained by these rules”

  • Type Constraint is interface that specify which types can be used as type parameters
    • Type Constraint defines what operations are allowed on type parameters
    • it specifies what kind of types are allowed when writing a generic function or type
// this is *TypeConstraint*
type Number interface {
	int32 | int64 | float32 | float64
}
 
// this is how it's used
func myFunc[T Number](num T) {}
 
// this is NOT how it's used
myArr := []Number{1, 2.2, 3}  // wrong!!! this is trying to use TypeConstraint as a real type!

up

down

reference