Reflection 如何使用reflect在golang中生成具有给定名称(字符串)的数组
我想在golang中创建名为的数组,但出现了一些错误 这是我的密码 包干管Reflection 如何使用reflect在golang中生成具有给定名称(字符串)的数组,reflection,go,Reflection,Go,我想在golang中创建名为的数组,但出现了一些错误 这是我的密码 包干管 import ( "fmt" "reflect" ) type My struct{ Name string Id int } func main() { my := &My{} myType := reflect.TypeOf(my) fmt.Println(myType) //v := reflect.New(myType).Elem().I
import (
"fmt"
"reflect"
)
type My struct{
Name string
Id int
}
func main() {
my := &My{}
myType := reflect.TypeOf(my)
fmt.Println(myType)
//v := reflect.New(myType).Elem().Interface()
// I want to make array with My
//a := make([](myType.(type),0) //can compile
//a := make([]v.(type),0) ////can compile
fmt.Println(a)
}
我相信这就是你想要的:
slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0).Interface()
工作示例:
slice := reflect.Zero(reflect.SliceOf(myType)).Interface()
注意:如果你想创建一个实际的数组(而不是一个切片),你将在Go 1.5(2015年8月)
reflect.ArrayOf
看了又看,修好了
reflect
:实现ArrayOf
此更改公开reflect.ArrayOf
以创建新的reflect.Type
数组
当给定reflect.Type
元素时,在运行时输入
:实现reflect
ArrayOf
:测试reflect
ArrayOf
:reflect使用的runtime
文档必须保存在 同步的typeAlg
但是我怎样才能附加到它上面呢?你可以使用
reflect.append
和AppendSlice
函数。@GustavoNiemeyer所以我尝试了你的方法,它看起来很不错,直到我尝试将指向该切片的指针发送到一个库中,它会破坏键入:(注意最后两个不匹配的事实)。
at1 := ArrayOf(5, TypeOf(string("")))
at := ArrayOf(6, at1)
v1 := New(at).Elem()
v2 := New(at).Elem()
v1.Index(0).Index(0).Set(ValueOf("abc"))
v2.Index(0).Index(0).Set(ValueOf("efg"))
if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
}