Pointers Can';不能得到反射而不返回指针,编译器在转换时会恐慌吗?
围绕这样的内容编写的代码导致了一个问题:Pointers Can';不能得到反射而不返回指针,编译器在转换时会恐慌吗?,pointers,reflection,go,interface,Pointers,Reflection,Go,Interface,围绕这样的内容编写的代码导致了一个问题: func CreateNewItemOfType(returnType reflect.Type) (interface {}) { return reflect.New(returnType).Interface(); } 。。。如何才能真正返回returnType的结构,而不是reflect在此处创建的指向结构的指针?编译器可以很好地构建这个函数,但在运行时会陷入恐慌,但不会在这里的返回调用前接受星号,以便实际返回结构而不是指针。创建指定
func CreateNewItemOfType(returnType reflect.Type) (interface {}) {
return reflect.New(returnType).Interface();
}
。。。如何才能真正返回returnType
的结构,而不是reflect
在此处创建的指向结构的指针?编译器可以很好地构建这个函数,但在运行时会陷入恐慌,但不会在这里的返回调用前接受星号,以便实际返回结构而不是指针。创建指定类型的新值,并返回指向该值的指针描述符。您可以使用从指针“导航”到封装在reflect.value
中的指向值。然后可以调用以获取值(struct)作为接口{}
值
func CreateNewItemOfType(returnType reflect.Type) interface{} {
return reflect.New(returnType).Elem().Interface()
}
如果需要具体类型的值,可以使用“提取”包装在接口{}
值中的值
func CreateNewItemOfType(returnType reflect.Type) interface{} {
return reflect.New(returnType).Elem().Interface()
}
测试它:
type Point struct {
X, Y int
}
t := reflect.TypeOf(Point{})
i := CreateNewItemOfType(t) // i is of type interface{}
fmt.Printf("%T %+v\n", i, i)
pt := i.(Point) // pt is of type Point
fmt.Printf("%T %+v\n", pt, pt)
输出(在上尝试):
注意:
如果未使用value.Elem()
,也可以获取非指针结构值。为此,需要键入assert指针值(类型为*Point
),然后可以取消对指针的引用以获取非指针
请参见此示例:
t := reflect.TypeOf(Point{})
pi := reflect.New(t).Interface() // pi is of type interface{}
fmt.Printf("%T %+v\n", pi, pi)
ppt := pi.(*Point) // pt is of type *Point
fmt.Printf("%T %+v\n", ppt, ppt)
i2 := *ppt // i2 is of type Point
fmt.Printf("%T %+v\n", i2, i2)
输出:
*main.Point &{X:0 Y:0}
*main.Point &{X:0 Y:0}
main.Point {X:0 Y:0}
@b是的,但是您可以调用
Value.Elem()
返回的Value
上的Value.Interface()
。它在答案中,读出来。@icza如果我这样做,那么它就是一个指针,如果我尝试“类型断言”它。。。它说它是那种类型的指针,而不是类型本身,我们回到了我原来的问题。@BenGuild你试过我在答案中包含的例子了吗?点击链接试试。输出是作为验证发布的。@BenGuild然后您应该发布更多的代码,以便我们可以判断出它的错误。@BenGuild请显示您的确切代码,以便我们可以帮助您。