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

How to use runtime type reflection to convert types?

王林
Release: 2024-02-06 10:51:12
forward
680 people have browsed it

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])))
    }
}
Copy after login

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))
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template