I want to make array with name in golang, but I got some error here is my code package 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)
}
I believe this is what you're looking for:
slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0).Interface()
Working example:
As a side note, in most cases a nil slice is more suitable than one with capacity zero. If you want a nil slice, this would do instead:
slice := reflect.Zero(reflect.SliceOf(myType)).Interface()
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
: implementArrayOf
This change exposes
reflect.ArrayOf
to create newreflect.Type
array types at runtime, when given areflect.Type
element.
reflect
: implementArrayOf
reflect
: tests forArrayOf
runtime
: document thattypeAlg
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)
}