Skip to content

Instantly share code, notes, and snippets.

@progrium
Created September 6, 2019 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save progrium/edd0f8bac978d9fb37c470459e291f89 to your computer and use it in GitHub Desktop.
Save progrium/edd0f8bac978d9fb37c470459e291f89 to your computer and use it in GitHub Desktop.
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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment