如何将reflect.New的返回值转换回原始类型 [英] 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 ?
我提供了
方法来获取
.org / pkg / reflect /#Value.Interfacerel =nofollow>
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)
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.
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)
这篇关于如何将reflect.New的返回值转换回原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!