drdot
drdot

Reputation: 3347

How can I cast type using runtime type reflection?

I am trying to build a function using generics, that converts a slice of interfaces into a slice of type T.

I came up with below:

func convertInterfaceArray[T any](input []any, res []T) {
    for _, item := range input {
        res = append(res, item.(reflect.TypeOf(res[0])))
    }
}

However, this will not compile. But you got the idea. T can be any type and I have an input slice of type []any that needs to be convert to []T

Upvotes: 0

Views: 62

Answers (1)

mindy
mindy

Reputation: 76

Assert the value to type T. Reflection is not required.

for _, item := range input {
    res = append(res, item.(T))
}

https://go.dev/play/p/cFn_nsVFIik

Upvotes: 6

Related Questions