What is the ~int type in go, and why is there a tilde in front of the type?

Preface

After go1.18introducing 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/constraintssomething 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 ~stringwhat is this? When I first saw it, I thought it was IDEsome auxiliary display added, but it was not the real character =-=.

explain

~int, ~stringAdding a wavy line before each type ~indicates a derived type, which typecan 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 minmethod to find the minimum value, customizes the MyIntand MyInt1types, 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 typecustom 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 gothe official package golang.org/x/exp/constraints.

Guess you like

Origin blog.csdn.net/DisMisPres/article/details/130701818