【问题标题】:How to I convert reflect.New's return value back to the original type如何将 reflect.New 的返回值转换回原始类型
【发布时间】:2015-12-04 23:01:41
【问题描述】:

我在 go 中使用反射,我注意到下面表达的奇怪:

package main

import (
        "log"
        "reflect"
)

type Foo struct {
        a int
        b int
}

func main() {
        t := reflect.TypeOf(Foo{})
        log.Println(t) // main.Foo
        log.Println(reflect.TypeOf(reflect.New(t))) // reflect.Value not main.Foo
}

如何将reflect.Value 转换回main.Foo

为方便起见,我提供了go playground

【问题讨论】:

    标签: go reflection go-reflect


    【解决方案1】:

    您使用Value.Interface 方法获取interface{},然后您可以使用类型断言来提取值:

    t := reflect.TypeOf(Foo{})
    val := reflect.New(t)
    newT := val.Interface().(*Foo)
    

    如果您不需要指针,则使用reflect.Zero 函数为该类型创建一个零值。然后,您使用相同的接口和类型断言方法来提取新值。

    t := reflect.TypeOf(Foo{})
    f := reflect.Zero(t)
    newF := f.Interface().(Foo)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      相关资源
      最近更新 更多