Set slice index using reflection in Go

I am in Go, working with reflection. Imagine the presentation of the fragment. I have the following:

slice := reflect.MakeSlice(typ, len, cap) 

If I want to get the ith value from slice , it's simple:

 v := slice.Index(i) // returns a reflect.Value 

However, I cannot find a way to set the i-th value. reflect.Value has many setter methods, for example, if I have a map, m , the following is possible:

 m.SetMapIndex(key, value) // key and value have type reflect.Value 

But there seems to be no equivalent for slices. I thought that perhaps the value returned from slice.Index(i) is actually a pointer, so calling v := slice.Index(i); v.Set(newV) v := slice.Index(i); v.Set(newV) will work? I'm not sure. Ideas?

+7
reflection slice go
source share
2 answers

I thought! It turns out I published it prematurely - I think that slice.Index(0) returns the pointer correctly. In particular:

 one := reflect.ValueOf(int(1)) slice := reflect.MakeSlice(reflect.TypeOf([]int{}), 1, 1) v := slice.Index(0) fmt.Println(v.Interface()) v.Set(one) fmt.Println(v.Interface()) v = slice.Index(0) fmt.Println(v.Interface()) 

prints:

 0 1 1 

(Here's the runnable code on the playground)

+13
source share

This can help:

 n := val.Len() if n >= val.Cap() { ncap := 2 * n if ncap < 4 { ncap = 4 } nval := reflect.MakeSlice(val.Type(), n, ncap) reflect.Copy(nval, val) val.Set(nval) } val.SetLen(n + 1) // ... val.Index(n).SetString("value") // Depends on type 

Taken from the library, I wrote some time ago github.com/webconnex/xmlutil , in particular decode.go.

0
source share

All Articles