如何使用反射在golang中使用给定名称(字符串)创建数组

时间:2013-09-04 02:05:57

标签: reflection go

我想在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)
}

2 个答案:

答案 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 4111commit 918fdaeSebastien Binet (sbinet),修正a 2013 issue 5996

  

reflect:实施ArrayOf

     

此更改公开reflect.ArrayOf以创建新的reflect.Type数组   在给定reflect.Type元素时,运行时的类型。

     
      
  • reflect:实施ArrayOf
  •   
  • reflect:测试ArrayOf
  •   
  • runtime:反映使用typeAlg的文件,必须保留   同步
  •   

允许for test like

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)
}