Guest User

Untitled

a guest
Jul 18th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. type hoge struct {
  9. name string
  10. }
  11.  
  12. func main() {
  13. s := []*hoge{}
  14. setToHogeSlice(&s)
  15. fmt.Println(s)
  16. }
  17.  
  18. func setToHogeSlice(v interface{}) {
  19. typ := reflect.TypeOf(v)
  20. if typ.Kind() != reflect.Ptr {
  21. panic("should be pointer of slice")
  22. }
  23. if typ.Elem().Kind() != reflect.Slice {
  24. panic("should be pointer of slice")
  25. }
  26.  
  27. val := reflect.ValueOf(v).Elem()
  28.  
  29. sliceValType := typ.Elem().Elem()
  30. newValType := sliceValType
  31. if sliceValType.Kind() == reflect.Ptr {
  32. newValType = sliceValType.Elem()
  33. }
  34.  
  35. newval := reflect.New(newValType)
  36. set(newval.Interface())
  37.  
  38. if sliceValType.Kind() == reflect.Ptr {
  39. val.Set(reflect.Append(val, newval))
  40. } else {
  41. val.Set(reflect.Append(val, newval.Elem()))
  42. }
  43. }
  44.  
  45. func set(v interface{}) {
  46. val := reflect.ValueOf(v)
  47. fmt.Println(val.Kind() == reflect.Ptr)
  48. fmt.Println(val.Elem().Kind())
  49. fmt.Println(val.Elem().CanAddr())
  50.  
  51. h := reflect.ValueOf(hoge{name: "AAAAAAAA"})
  52. fmt.Println(val.Elem().Kind())
  53. val.Elem().Set(h)
  54. }
Add Comment
Please, Sign In to add comment