Type Constraints
Start with Type Constraints
Constraints describe the set of types allowed for a type parameter and the operations available on those values.
What you’ll learn
- Explain the main purpose of type constraints.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
With [T ~int | ~int64], the ~ permits defined types whose underlying type is int or int64. A union constraint lets the body use operations supported by every term, such as addition for these numeric types.
The predeclared comparable constraint permits equality and map-key use; it does not imply ordering. For ordered values you can use an appropriate ordered constraint or a comparison function. Avoid inventing extremely broad unions that obscure behavior.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
type Score int
type Whole int64
type Integer interface{ ~int | ~int64 }
func add[T Integer](a, b T) T { return a + b }
func main() {
fmt.Println("Score:", add(Score(2), Score(5)))
fmt.Println("Whole:", add(Whole(10), Whole(15)))
}
Output
Score: 7
Whole: 25Trace what the program does
Both defined types have underlying types permitted by Integer. The generic addition preserves each named type, so the results are 7 and 25.
Avoid common mistakes
- Without ~, a union term int denotes that exact type, not all new named types with int underlying type.
- comparable does not allow the less-than operator.
Try it yourself
Expand Integer with ~int32 and test a defined type based on int32.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Type Constraints in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.