Essential Go Reflection  Edit on GitHub      File Issue

Slice

Read a slice using reflection

a := []int{3, 1, 8}
rv := reflect.ValueOf(a)

fmt.Printf("len(a): %d\n", rv.Len())
fmt.Printf("cap(a): %d\n", rv.Cap())

fmt.Printf("slice kind: '%s'\n", rv.Kind().String())

fmt.Printf("element type: '%s'\n", rv.Type().Elem().Name())

el := rv.Index(0).Interface()
fmt.Printf("a[0]: %v\n", el)

elRef := rv.Index(1)
fmt.Printf("elRef.CanAddr(): %v\n", elRef.CanAddr())
fmt.Printf("elRef.CanSet(): %v\n", elRef.CanSet())

elRef.SetInt(5)
fmt.Printf("a: %v\n", a)
len(a): 3
cap(a): 3
slice kind: 'slice'
element type: 'int'
a[0]: 3
elRef.CanAddr(): true
elRef.CanSet(): true
a: [3 5 8]

Creating a new slice using reflection

typ := reflect.SliceOf(reflect.TypeOf("example"))
// create slice with capacity 10 and length 1
rv := reflect.MakeSlice(typ, 1, 10)
rv.Index(0).SetString("foo")

a := rv.Interface().([]string)
fmt.Printf("a: %#v\n", a)
a: []string{"foo"}
  ↑ ↓ to navigate     ↵ to select     Esc to close