如何将 reflect.New 的 return 值转换回原始类型

How to I convert reflect.New's return value back to the original type

我在 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

你使用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)