Home > Backend Development > Golang > How Does the ~ Token in Go Generics Handle Underlying Types?

How Does the ~ Token in Go Generics Handle Underlying Types?

Mary-Kate Olsen
Release: 2024-12-14 21:35:12
Original
292 people have browsed it

How Does the ~ Token in Go Generics Handle Underlying Types?

Understanding the Tilde (~) Token in Go Generics

Go has introduced the new token ~, representing the set of types with underlying type T.

Definition

The ~T token denotes a constraint element that specifies the set of types whose underlying type is T.

Example

Consider the following example:

type Ordered interface {
    Integer | Float | ~string
}
Copy after login

In this example, the ~string constraint element means that a type must have an underlying type of string to satisfy the Ordered interface.

Underlying Types

The definition of underlying types is crucial to understanding the behavior of ~T constraint elements. The language spec defines underlying types as follows:

  • For predeclared numeric, boolean, or string types, or type literals, their underlying type is themselves.
  • For other types, their underlying type is the underlying type of the type to which they refer in their type declaration.

Practical Implications

The practical implication of the ~T token is that it allows your custom types to be used in interfaces and constraints, even if those interfaces and constraints specify exact types. For instance, consider the following code:

type MyInt8 int8

// Cannot instantiate with MyInt8
func echoExact[T constraints.ExactSigned](t T) T { return t }

// Can instantiate with MyInt8
func echo[T constraints.Signed](t T) T { return t }
Copy after login

In this example, the constraints.ExactSigned type does not allow custom types, while the constraints.Signed type does due to the use of the ~T constraint element.

Conclusion

The ~T token provides a flexible way to specify type constraints in Go generics. It enables the use of custom types that have underlying types matching the specified constraint, enhancing the expressiveness and usability of generic code.

The above is the detailed content of How Does the ~ Token in Go Generics Handle Underlying Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template