How to make an array with a given name (string) in golang with reflection

I want to create an array with a name in golang, but I got some error here is my code main package

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
source share
2 answers

I believe this is what you are looking for:

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

Working example:

As a side note, in most cases a zero slice is more suitable than a zero power unit. If you want zero, then this will do instead:

  slice := reflect.Zero(reflect.SliceOf(myType)).Interface() 
+6
source

Note. If you want to create an actual array (not a fragment), you will have reflect.ArrayOf in Go 1.5 (August 2015).

See recall 4111 and transfer 918fdae Sebastien Binet ( sbinet ) , correcting the September 5996 release .

reflect : implement ArrayOf

This change provides reflect.ArrayOf to create a new array of reflect.Type types at run time if the reflect.Type element is reflect.Type .

  • reflect : implement ArrayOf
  • reflect : tests for ArrayOf
  • runtime : a document that typeAlg used by reflection and should be kept in sync

This allows for a test, for example :

 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) } 
+1
source

Source: https://habr.com/ru/post/1500419/


All Articles