6

我想在 golang 中用名称制作数组,但我遇到了一些错误,这是我的代码包 main

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

2 回答 2

8

我相信这就是您正在寻找的:

 slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0).Interface()

工作示例:

作为旁注,在大多数情况下,零切片比容量为零的切片更合适。如果你想要一个 nil 切片,可以这样做:

 slice := reflect.Zero(reflect.SliceOf(myType)).Interface()
于 2013-09-04T02:37:43.170 回答
4

Note: if you want to create an actual array (and not a slice), you will have in Go 1.5 (August 2015) reflect.ArrayOf.

See review 4111 and commit 918fdae by Sebastien Binet (sbinet), fixing a 2013 issue 5996.

reflect: implement ArrayOf

This change exposes reflect.ArrayOf to create new reflect.Type array types at runtime, when given a reflect.Type element.

  • reflect: implement ArrayOf
  • reflect: tests for ArrayOf
  • runtime: document that typeAlg is used by reflect and must be kept in synchronized

That allows 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)
}
于 2015-04-22T05:31:40.213 回答