Last active
October 15, 2018 09:51
-
-
Save u007/1a0fb300700b312bfb236609cb140166 to your computer and use it in GitHub Desktop.
golang setting pointer slice with reflect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/LYaSVFcVDxM