Skip to Content
Course content

173: Type Sets and Constraints Package

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 cmp package.
  • 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)) 
Rating
0 0

There are no comments for now.

to be the first to leave a comment.