Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ~ (tilde) operator in Go is an approximation symbol used exclusively within generic type constraints. Introduced in Go 1.18, the expression ~T specifies that a type parameter accepts any type whose underlying type is exactly T. Without the ~ operator, a type constraint requires a strict type match. With the ~ operator, the compiler evaluates the underlying type of the provided type argument against T to determine if the constraint is satisfied.

Syntax

The ~ operator is placed directly before a valid type within an interface or a type parameter list:
// Inline constraint using ~
func Process[T ~int](val T) {
    // Implementation details
}

// Interface constraint using ~
type Number interface {
    ~int | ~int32 | ~int64 | ~float64
}

Mechanics of Underlying Types

In Go, you can declare defined types based on existing types. The ~ operator dictates how these defined types are evaluated against constraints.
type UserID int
type SessionID int
  • Strict Constraint (int): Only accepts the exact type int. Passing UserID or SessionID results in a compiler error.
  • Approximation Constraint (~int): Accepts int, UserID, and SessionID because the underlying type for all three is int.

Rules and Restrictions

  1. Underlying Type Must Be Itself: The type T in ~T must be a type whose underlying type is itself. This restricts T to predeclared types (such as int, string, float64) or type literals (such as []string, map[int]bool). You cannot use a defined type that resolves to another underlying type. For example, if type MyInt int, using ~MyInt results in a compiler error: invalid use of ~ (underlying type of MyInt is int).
  2. No Interfaces: The type T cannot be an interface type. Applying the tilde to an interface (e.g., ~error) is invalid.
  3. No Type Parameters: You cannot apply the tilde to a type parameter (e.g., type Constraint[T any, U ~T] is invalid).
  4. Constraint Scope: The ~ operator is strictly a compile-time construct for type constraints. It cannot be used in variable declarations, type assertions, or runtime reflection.

Disambiguation: Bitwise NOT

Developers transitioning from C, C++, Java, or C# often expect ~ to function as the bitwise NOT (complement) operator. Go does not use ~ for bitwise operations. To perform a bitwise NOT in Go, use the caret (^) as a unary operator:
func BitwiseNotExample() {
    var y int = 42
    var x int = ^y // Equivalent to ~y in C/C++/Java
}
Master Go with Deep Grasping Methodology!Learn More