~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
- a type constraint
// ~ 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
MyIntintoGetInt:
myInt := MyInt(1)
normalInt := GetInt(MyInt)-
this won't work!
- because type
MyIntis NOTint64orfloat64
- because type
-
but the underlying type of
MyIntIS actuallyint64tho! -
that’s when we have:
type Number interface {
~int64 | ~float64
}
// same code as above
normalInt := GetInt(myInt)- now this works!
~int64means: “any type whose underlying type isint64”
- this works too!
- the essence of
~is that it’s used on type constraint
func GetInt[T ~int64 | ~float64](num T) {
// some code
}