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

痴心易碎 提交于 2019-12-10 22:55:33

问题


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:


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)


来源:https://stackoverflow.com/questions/34098936/how-to-i-convert-reflect-news-return-value-back-to-the-original-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!