我想在golang中使用name创建数组,但是我遇到了一些错误 这是我的代码 包主要
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)
}
答案 0 :(得分:6)
我相信这就是你要找的东西:
slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0).Interface()
工作示例:
作为旁注,在大多数情况下,零切片比容量为零的切片更合适。如果你想要一个零片,那就改为:
slice := reflect.Zero(reflect.SliceOf(myType)).Interface()
答案 1 :(得分:2)
注意:如果您想创建一个实际的数组(而不是切片),您将在Go 1.5(2015年8月) reflect.ArrayOf
中使用。
review 4111见commit 918fdae和Sebastien Binet (sbinet
),修正a 2013 issue 5996。
reflect
:实施ArrayOf
此更改公开
reflect.ArrayOf
以创建新的reflect.Type
数组 在给定reflect.Type
元素时,运行时的类型。
reflect
:实施ArrayOf
reflect
:测试ArrayOf
runtime
:反映使用typeAlg
的文件,必须保留 同步
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)
}