2

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.

4

1 回答 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)
于 2015-12-04T23:17:09.453 回答