package main
import (
"fmt"
"reflect"
)
func main() {
type tu struct {
N int
}
type t struct {
ARRAY []tu
NESTED *tu
NESTED_ARRAY []*tu
}
var n = t{[]tu{{4}}, &tu{5}, []*tu{{6}}}
//print value
fmt.Printf("value2: %v\n", reflect.ValueOf(&n).Elem().Field(1).Slice(0, 1))
fmt.Printf("value3: %v\n", reflect.ValueOf(&n).Elem().Field(2).Elem().Field(0))
fmt.Printf("value4: %v\n", reflect.ValueOf(&n).Elem().Field(3).Slice(0, 1).Elem().Field(0))
return
}
I'm trying to access the value of a slice pointer using reflection.
reflect.ValueOf(&n).Elem().Field(3).Slice(0, 1).Elem().Field(0)
should work but it doesn't.
How should I go around doing this?
Field index starts with 0
, not 1
. So decrease all indices by 1.
And in your last example the Value.Slice()
call returns a slice, not a pointer (not an element of the slice, but a subslice). If you need an element, call Value.Index()
on that, then you can call Elem()
and Field()
:
fmt.Printf("value2: %v\n", reflect.ValueOf(&n).Elem().Field(0).Slice(0, 1))
fmt.Printf("value3: %v\n", reflect.ValueOf(&n).Elem().Field(1).Elem().Field(0))
fmt.Printf("value4: %v\n", reflect.ValueOf(&n).Elem().Field(2).Slice(0, 1).Index(0).Elem().Field(0))
This will output (try it on the Go Playground):
value2: [{4}]
value3: 5
value4: 6
Also note that the Value.Slice()
method is equivalent to a slicing expression. If you need an element, just call Value.Index()
, you don't need the Slice()
method:
fmt.Printf("value2: %v\n", reflect.ValueOf(&n).Elem().Field(0).Index(0))
fmt.Printf("value3: %v\n", reflect.ValueOf(&n).Elem().Field(1).Elem().Field(0))
fmt.Printf("value4: %v\n", reflect.ValueOf(&n).Elem().Field(2).Index(0).Elem().Field(0))
This will output (try this one on the Go Playground):
value2: {4}
value3: 5
value4: 6