~Type in Go

tags: learning go programming

content

Note

~ is for generics and type constraints
(aka, make the connection: whenever ~ is involved, it’s in the context of generics and type constraints)

  • imagine we have:
    • a type constraint Number
    • a named type MyInt
    • a generic function GetInt
// ~ is in the context of generics and type constraint!
// so let's define a type constraint:
type Number interface {
	int64 | float64
}
type MyInt int64
func GetInt[T Number](num T) int {
	return int(num)
}
  • we wanna pass MyInt into GetInt:
myInt := MyInt(1)
normalInt := GetInt(MyInt)
  • this won't work!

    • because type MyInt is NOT int64 or float64
  • but the underlying type of MyInt IS actually int64 tho!

  • that’s when we have:

type Number interface {
	~int64 | ~float64
}
// same code as above
normalInt := GetInt(myInt)
  • now this works!
  • ~int64 means: “any type whose underlying type is int64

  • this works too!
  • the essence of ~ is that it’s used on type constraint
func GetInt[T ~int64 | ~float64](num T) {
	// some code
}

up

down

reference