Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "reflect"
- )
- type hoge struct {
- name string
- }
- func main() {
- s := []*hoge{}
- setToHogeSlice(&s)
- fmt.Println(s)
- }
- func setToHogeSlice(v interface{}) {
- typ := reflect.TypeOf(v)
- if typ.Kind() != reflect.Ptr {
- panic("should be pointer of slice")
- }
- if typ.Elem().Kind() != reflect.Slice {
- panic("should be pointer of slice")
- }
- val := reflect.ValueOf(v).Elem()
- sliceValType := typ.Elem().Elem()
- newValType := sliceValType
- if sliceValType.Kind() == reflect.Ptr {
- newValType = sliceValType.Elem()
- }
- newval := reflect.New(newValType)
- set(newval.Interface())
- if sliceValType.Kind() == reflect.Ptr {
- val.Set(reflect.Append(val, newval))
- } else {
- val.Set(reflect.Append(val, newval.Elem()))
- }
- }
- func set(v interface{}) {
- val := reflect.ValueOf(v)
- fmt.Println(val.Kind() == reflect.Ptr)
- fmt.Println(val.Elem().Kind())
- fmt.Println(val.Elem().CanAddr())
- h := reflect.ValueOf(hoge{name: "AAAAAAAA"})
- fmt.Println(val.Elem().Kind())
- val.Elem().Set(h)
- }
Add Comment
Please, Sign In to add comment