【问题标题】:How can I cast type using runtime type reflection?如何使用运行时类型反射来转换类型?
【发布时间】:2022-11-29 12:11:26
【问题描述】:

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

我想出了以下:

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

但是,这不会编译。但是你明白了。 T 可以是任何类型,我有一个 []any 类型的输入切片需要转换为 []T

【问题讨论】:

    标签: go generics interface


    【解决方案1】:

    断言该值以键入 T。不需要反思。

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

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

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 2011-02-28
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      相关资源
      最近更新 更多