Generics Basics
Type Constraints
A constraint limits which types a generic function can accept.
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.
Type Constraints
type_constraints.go
Replay: real traced execution (multi-file project)
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 = 4
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 = 2
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 = 7
doubled := TwiceInt(count)
fmt.Println("count=", count)
fmt.Println("doubled=", doubled)
fmt.Println("type=", fmt.Sprintf("%T", doubled))
}
count ← 4
10func main() {11 var count→ 4 = 4 //@count=2, 712 doubled := TwiceInt(count4)func TwiceInt(value int) int
5// Generic shape: Twice[T ~int | ~float64](value T) T6func TwiceInt(value4 int) int {7 return value4 + value8}doubled ← 8
11 var count = 4 //@count=2, 712 doubled→ 8 := TwiceInt(count4)1314 fmt.Println("count=", count4)15 fmt.Println("doubled=", doubled8)16 fmt.Println("type=", fmt.Sprintf("%T", doubled8))17}outputcount= 4 doubled= 8 type= int
count ← 2
10func main() {11 var count→ 2 = 212 doubled := TwiceInt(count2)func TwiceInt(value int) int
5// Generic shape: Twice[T ~int | ~float64](value T) T6func TwiceInt(value2 int) int {7 return value2 + value8}doubled ← 4
11 var count = 212 doubled→ 4 := TwiceInt(count2)1314 fmt.Println("count=", count2)15 fmt.Println("doubled=", doubled4)16 fmt.Println("type=", fmt.Sprintf("%T", doubled4))17}outputcount= 2 doubled= 4 type= int
count ← 7
10func main() {11 var count→ 7 = 712 doubled := TwiceInt(count7)func TwiceInt(value int) int
5// Generic shape: Twice[T ~int | ~float64](value T) T6func TwiceInt(value7 int) int {7 return value7 + value8}doubled ← 14
11 var count = 712 doubled→ 14 := TwiceInt(count7)1314 fmt.Println("count=", count7)15 fmt.Println("doubled=", doubled14)16 fmt.Println("type=", fmt.Sprintf("%T", doubled14))17}outputcount= 7 doubled= 14 type= int