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)
}
To create String Array, which is to declare and initialize in a single line, we can use the syntax of array to declare and initialize in one line as shown in the following. arrayName is the variable name for this string array. arraySize is the number of elements we would like to store in this string array.
You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.
To add an element to a slice in go, we can use the append() method. The append() method takes the name of the slice and the new element to add. In the example above, we add the element “David” to the slice “my_slice”.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With