Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "reflect"
- )
- type MyInterface interface {
- Foo() string
- }
- type TypeA struct {
- ID string
- }
- func (o *TypeA) Foo() string {
- return o.ID
- }
- type TypeB struct {
- ID string
- }
- func findValue(rv reflect.Value) {
- objs := []interface{}{
- &TypeB{"one"},
- &TypeB{"two"},
- &TypeA{"MEEE"},
- &TypeB{"three"},
- }
- //fmt.Printf("%s\n", rv.Elem().Type().Kind())
- //rv := reflect.ValueOf(v)
- for _, obj := range objs {
- robj := reflect.ValueOf(obj)
- if rv.Elem().Type().Kind() == reflect.Struct {
- if robj.Elem().Type().AssignableTo(rv.Elem().Type()) {
- rv.Elem().Set(robj.Elem())
- break
- }
- } else {
- //fmt.Println(rv.Elem().Type())
- if robj.Type().Implements(rv.Elem().Type()) {
- rv.Elem().Set(robj)
- break
- }
- }
- }
- }
- type T struct {
- F MyInterface
- }
- func main() {
- var i MyInterface
- //fmt.Printf("%#v\n", i)
- //fmt.Printf("%#v\n", &i)
- findValue(reflect.ValueOf(&i))
- fmt.Println(i)
- var t TypeA
- findValue(reflect.ValueOf(&t))
- fmt.Println(t)
- rt := reflect.TypeOf(&T{})
- rf, _ := rt.Elem().FieldByName("F")
- v := reflect.New(rf.Type)
- //fmt.Printf("%#v\n", v)
- findValue(v)
- fmt.Println(reflect.Indirect(v).Interface())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement