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
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!