Home  >  Article  >  Backend Development  >  How to use runtime type reflection to convert types?

How to use runtime type reflection to convert types?

王林
王林forward
2024-02-06 10:51:12641browse

How to use runtime type reflection to convert types?

Question content

I'm trying to build a function using generics that converts an interface slice into a slice of type t.

I came up with the following:

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 get the point. t can be of any type, I have an input slice of type []any that needs to be converted to []t


Correct Answer


Assertion Typet value. No reflection required.

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

https://www.php.cn/link/f2a13eeae490ef805070086405e26087

The above is the detailed content of How to use runtime type reflection to convert types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete