Skip to content

Instantly share code, notes, and snippets.

@u007
Last active October 15, 2018 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u007/1a0fb300700b312bfb236609cb140166 to your computer and use it in GitHub Desktop.
Save u007/1a0fb300700b312bfb236609cb140166 to your computer and use it in GitHub Desktop.
golang setting pointer slice with reflect
package main
import (
"fmt"
"reflect"
)
type X struct {
Name string
Values *[]Y
}
type Y struct {
Name string
}
func main() {
x := X{}
//t := reflect.TypeOf(x)
val := reflect.ValueOf(x)
vals := val.FieldByName("Values")
tY := vals.Type().Elem()//get non pointer - []Y
point := reflect.New(tY)
fmt.Printf("point: %#v\n", point)
elem := point.Elem()
elem.Set(reflect.MakeSlice(tY, 0, 0))
fmt.Printf("point: %#v\n", point)
newSlice := reflect.New(tY.Elem())//get Y
elem.Set(reflect.Append(elem, newSlice.Elem()))
fmt.Printf("Hello, playground %#v\n%#v\n", tY, point)
}
@u007
Copy link
Author

u007 commented Oct 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment