你可以使用运行时类型反射来进行类型转换。

huangapple go评论70阅读模式
英文:

How can I cast type using runtime type reflection?

问题

我正在尝试使用泛型构建一个函数,将接口切片转换为类型为 T 的切片。

我想到了以下代码:

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

然而,这段代码无法编译通过。但你已经有了思路。T 可以是任何类型,我有一个类型为 []any 的输入切片,需要转换为 []T。

英文:

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

答案1

得分: 6

为了断言值的类型为 T,不需要使用反射。

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

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

英文:

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

huangapple
  • 本文由 发表于 2022年11月29日 11:33:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/74608886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定