Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
173: Type Sets and Constraints Package
Imagine you're organizing a high-end dinner party. You don't just open the doors to anyone; you have a guest list. Some guests are invited because of who they are (their specific name), while others are invited because they hold a certain status (like "anyone with a Platinum Membership"). If someone shows up with a Platinum card, it doesn't matter if their name isn't explicitly on the list—they're in.
In Go, a Type Set is that guest list. When we use interfaces as constraints in generics, we aren't just talking about methods anymore. We're defining a set of permissible types that are allowed to "plug into" our function. The constraints package (and the more modern cmp package in the standard library) essentially provides the "Platinum Membership" lists so you don't have to manually type out every single single numeric type every time you want to compare two values.
Defining the Guest List
Before generics, interfaces were all about behavior—what a type could do. With type sets, interfaces can also describe what a type is. You do this by listing types separated by a pipe | symbol.
type Number interface {
int | int64 | float64
}
func Sum[T Number](a, b T) T {
return a + b
}
In this example, Number is our type set. If you try to pass a string into Sum, the compiler will stop you immediately because string isn't on the guest list. I've found that this is where most developers first hit a wall: you can't use operators like + or < on a generic type unless the constraint explicitly limits the type set to types that support those operations.
The Tilde Trick for Custom Types
Here is where it gets interesting. What happens if you define your own type, like type MyInt int? Even though MyInt is basically an integer, it's technically a distinct type. If our guest list only says int, MyInt gets rejected at the door.
To fix this, we use the tilde ~ symbol. This tells Go: "Allow any type whose underlying type is this."
type Number interface {
~int | ~int64 | ~float64
}
type MyInt int
// This now works because ~int covers MyInt
func Add[T Number](a, b T) T {
return a + b
}
I always recommend using the tilde when building libraries. It makes your generic functions much more flexible for the people using them, as they can use their own domain-specific types without you having to know about them in advance.
Letting the Standard Library Do the Heavy Lifting
Writing ~int | ~int8 | ~int16 | ~int32 | ~int64 ... is tedious and error-prone. You'll likely miss one. This is why the cmp package (introduced in Go 1.21) and the golang.org/x/exp/constraints package exist.
The cmp.Ordered constraint is the one you'll use most often. It includes all types that support the <, >, <=, and >= operators. Instead of building your own "Ordered" list, you just use theirs.
import "cmp"
func GetMax[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
It's clean, it's standard, and it saves you from writing a dozen lines of type unions. I've seen plenty of teams try to roll their own constraints package, but unless you have a very weird edge case, sticking to cmp.Ordered or cmp.Comparable is the way to go.
📋 Practical Task
Build a Generic "Range-Check" Utility
Your task is to create a utility function called IsWithinRange. This function should take three arguments: a value, a minimum bound, and a maximum bound. It should return true if the value is between the bounds (inclusive) and false otherwise.
Requirements:
- Use a generic type constraint that allows any ordered type (ints, floats, and strings). Use the
cmppackage. - Ensure the function works with custom types (e.g.,
type Temperature float64). - Implement the logic using the
<=and>=operators.
Test your implementation with these cases:
// Should be true
IsWithinRange(10, 1, 20)
// Should be true
IsWithinRange("banana", "apple", "cherry")
// Should be true (using a custom type)
type Celsius float64
IsWithinRange(Celsius(22.5), Celsius(10.0), Celsius(30.0))
There are no comments for now.