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

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

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

英文:

I'm using reflection in go and I noticed the oddity expressed below:

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
}

How can I convert the reflect.Value back to main.Foo?

I've provided a go playground for convenience.

答案1

得分: 8

你可以使用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)
英文:

You use the Value.Interface method to get an interface{}, then you can use a type assertion to extract value:

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

If you don't want a pointer, you use the reflect.Zero function to create a zero-value for the type. You then use the same interface and type assertion method to extract the new value.

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

huangapple
  • 本文由 发表于 2015年12月5日 07:01:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/34098936.html
匿名

发表评论

匿名网友

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

确定