Generics Basics
Type Constraints
A constraint limits which types a generic function can accept.
Type Constraints
type_constraints.go
package main
import "fmt"
// Generic shape: Twice[T ~int | ~float64](value T) T
func TwiceInt(value int) int {
return value + value
}
func main() {
var count =
doubled := TwiceInt(count)
fmt.Println("count=", count)
fmt.Println("doubled=", doubled)
fmt.Println("type=", fmt.Sprintf("%T", doubled))
}
package main
import "fmt"
// Generic shape: Twice[T ~int | ~float64](value T) T
func TwiceInt(value int) int {
return value + value
}
func main() {
var count =
doubled := TwiceInt(count)
fmt.Println("count=", count)
fmt.Println("doubled=", doubled)
fmt.Println("type=", fmt.Sprintf("%T", doubled))
}
package main
import "fmt"
// Generic shape: Twice[T ~int | ~float64](value T) T
func TwiceInt(value int) int {
return value + value
}
func main() {
var count =
doubled := TwiceInt(count)
fmt.Println("count=", count)
fmt.Println("doubled=", doubled)
fmt.Println("type=", fmt.Sprintf("%T", doubled))
}
constraint
A constraint describes the operations that are valid for a type parameter. The trace uses a concrete integer helper and shows the constrained generic shape in a comment.