voy*_*ech 4 reflection go slice
我想递归地迭代结构定义,并为切片获取单一元素的类型。然后,创建该类型的空实例。例如:
type Path struct {
Name string
Points []Coordinate
}
type Coordinate struct {
Latitude float64
Longitude float64
}
Run Code Online (Sandbox Code Playgroud)
假设类型在运行时未知,我如何创建嵌套类型的空实例(在上面的示例中坐标)。我是说:
x := Coordinate{}
当输入时我得到 Path (可以是任何其他结构,具有不同类型的切片)?
如果您有reflect.Type某个值的描述符,您可以使用reflect.New()函数来获取指向新的归零值的指针。
这将返回您一个reflect.Value值。这将是一个指针,要获取所reflect.Value指向对象的 ,请使用Value.Elem()。要“解开”内部保存的值reflect.Value(),您可以使用Value.Interface()。
因此,如果您有reflect.Type切片的描述符,则可以使用它Type.Elem()来获取reflect.Type切片的元素类型的描述符。
看这个例子:
p := Path{
Name: "foo",
Points: []Coordinate{
{1.1, 2.2},
{3.3, 4.4},
},
}
v := reflect.ValueOf(p)
f := v.FieldByName("Points")
cv := reflect.New(f.Type().Elem()).Elem()
c := cv.Interface()
fmt.Printf("%#v\n", c)
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上尝试):
main.Coordinate{Latitude:0, Longitude:0}
Run Code Online (Sandbox Code Playgroud)