Preface
After go1.18
introducing generics and understanding their basic syntax, the previous code was refactored using generics. It has been relatively empty recently, and I am going to optimize the generic-related code. When browsing the source code, I found golang.org/x/exp/constraints
something strange ( ~
) in the package, as follows:
type Ordered interface {
Integer | Float | ~string
}
This way of writing is understood to be generic syntax, and custom type constraints can be directly aggregated, but ~string
what is this? When I first saw it, I thought it was IDE
some auxiliary display added, but it was not the real character =-=.
explain
~int, ~string
Adding a wavy line before each type ~
indicates a derived type, which type
can be recognized even if a custom type is used ( type MyInt int
), as long as the underlying types are consistent.
Example
The following example provides a min
method to find the minimum value, customizes the MyInt
and MyInt1
types, and executes the generic method. It can be seen that the return value can be correctly output.
package main
import (
"fmt"
"golang.org/x/exp/constraints"
)
type MyInt = int
type MyInt1 int
func min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
func min1[T ~int](a, b T) T {
if a < b {
return a
}
return b
}
func main() {
fmt.Println(min(MyInt(1), MyInt(2)))
fmt.Println(min1(MyInt1(1), MyInt1(2)))
}
Summarize
This article introduces a small feature of generics ~
. The writing method of adding a wavy line before this type indicates a derived type. Even if a type
custom type is used, it can be recognized ( type MyInt int
), as long as the underlying type is the same. It is mainly the same as Used with generics.
Usually when using this type of sorting, you can directly use go
the official package golang.org/x/exp/constraints
.