Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. type MyInterface interface {
  9. Foo() string
  10. }
  11.  
  12. type TypeA struct {
  13. ID string
  14. }
  15.  
  16. func (o *TypeA) Foo() string {
  17. return o.ID
  18. }
  19.  
  20. type TypeB struct {
  21. ID string
  22. }
  23.  
  24. func findValue(rv reflect.Value) {
  25. objs := []interface{}{
  26. &TypeB{"one"},
  27. &TypeB{"two"},
  28. &TypeA{"MEEE"},
  29. &TypeB{"three"},
  30. }
  31. //fmt.Printf("%s\n", rv.Elem().Type().Kind())
  32. //rv := reflect.ValueOf(v)
  33. for _, obj := range objs {
  34. robj := reflect.ValueOf(obj)
  35. if rv.Elem().Type().Kind() == reflect.Struct {
  36. if robj.Elem().Type().AssignableTo(rv.Elem().Type()) {
  37. rv.Elem().Set(robj.Elem())
  38. break
  39. }
  40. } else {
  41. //fmt.Println(rv.Elem().Type())
  42. if robj.Type().Implements(rv.Elem().Type()) {
  43. rv.Elem().Set(robj)
  44. break
  45. }
  46. }
  47. }
  48. }
  49.  
  50. type T struct {
  51. F MyInterface
  52. }
  53.  
  54. func main() {
  55.  
  56. var i MyInterface
  57. //fmt.Printf("%#v\n", i)
  58. //fmt.Printf("%#v\n", &i)
  59. findValue(reflect.ValueOf(&i))
  60. fmt.Println(i)
  61.  
  62. var t TypeA
  63. findValue(reflect.ValueOf(&t))
  64. fmt.Println(t)
  65.  
  66. rt := reflect.TypeOf(&T{})
  67. rf, _ := rt.Elem().FieldByName("F")
  68.  
  69. v := reflect.New(rf.Type)
  70. //fmt.Printf("%#v\n", v)
  71. findValue(v)
  72. fmt.Println(reflect.Indirect(v).Interface())
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement