Home > Back-end >  How to convert `type Int32 int32` to `int32`?
How to convert `type Int32 int32` to `int32`?

Time:11-26

We have the following code that's generated (so we can't change it to type Enum interface { int32 }):

type Enum int32

There are a bunch of these type definitions to int32.

I'm trying to create a generic function that can convert a slice of such type definitions to a []int32:

func ConvertToInt32Slice[T int32](ts []T) []int32 {
    return lo.Map(ts, func(t T, _ int) int32 {
        return int32(t)
    })
}

but the following complains with Type does not implement constraint 'interface{ int32 }' because type is not included in type set ('int32'):

type Int32 int32
var int32s []Int32
i32s := ConvertToInt32Slice(int32s)

What's needed to implement the generic function so it can be used as intended?

CodePudding user response:

It looks like you want a generic function that operates on all types that have the underlying type int32. That's what the tilde (~) token is for. You should change the signature of your function to:

func ConvertToInt32Slice[T ~int32](ts []T) []int32

See also: What's the meaning of the new tilde token ~ in Go?

constraints.Integer also works, because that is defined as:

type Integer interface {
    Signed | Unsigned
}

https://pkg.go.dev/golang.org/x/exp/constraints#Integer

which is defined as:

type Signed interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
    ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

So that gives you all types that have any of the integer types as the underlying types.

If you're only interested in types that have int32 as their underlying type, you should use ~int32.

CodePudding user response:

Use constraints:

func ConvertToInt32Slice[T constraints.Integer](ts []T) []int32 {
    return lo.Map(ts, func(t T, _ int) int32 {
        return int32(t)
    })
}
  • Related