Build type sets with unions and approximation
Build type sets with unions and approximation
A constraint interface can describe a set of types. A union uses | to permit alternatives. A term ~int includes types whose underlying type is int; int alone includes just int. Multiple embedded constraint elements intersect their sets. Such non-basic interfaces are constraints, not ordinary runtime variable types.
package main
import ( "fmt")
type Number interface{ ~int | ~float64 }type Points int
func add[T Number](a, b T) T { return a + b }func main() { fmt.Println(add(Points(4), Points(5)), add(1.5, 2.0))}The approximation term admits Points because its underlying type is int. Both operands must agree on T. The result retains Points rather than converting to int. A union must obey restrictions including nonoverlapping non-interface terms.
Expected output:
9 3.5Intersect a type term and a method
package main
import ( "fmt")
type Scored interface { ~int Label() string}type Score int
func (s Score) Label() string { return "score" }func describe[T Scored](x T) string { return fmt.Sprintf("%s:%d", x.Label(), x) }func main() { fmt.Println(describe(Score(7)))}T must have underlying int and a matching Label method. An ordinary int lacks Label, while a string-based type with Label fails the underlying-type requirement. Use constraints to express the real operations, not a broad list of unrelated types.
Expected output:
score:7Try it locally
Define a constraint ~string|~int and a join function using +. Call it with a defined string type and print GoLang.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 04: Build type sets with unions and approximation
Check the lesson objective before moving on.
What does ~int admit?
What happens when a constraint contains ~int and Label() string?