Created
October 25, 2013 16:31
-
-
Save teaplanet/7157576 to your computer and use it in GitHub Desktop.
Invoke 'Method' method, expects 3 fields.
But, actually return a field via 'Call' method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| ) | |
| type I interface { | |
| Call() | |
| Method(interface{}) | |
| } | |
| type A struct { | |
| a1 bool | |
| } | |
| func (a *A) Call() { | |
| a.Method(a) | |
| } | |
| func (a *A) Method(i interface{}) { | |
| ip := reflect.ValueOf(i) | |
| iv := ip.Elem() | |
| fmt.Println("name:", iv.Type().Name()) | |
| for ii := 0; ii < iv.NumField(); ii++ { | |
| fmt.Println(iv.Field(ii)) | |
| } | |
| } | |
| type B struct { | |
| A | |
| b1 int | |
| b2 float32 | |
| b3 bool | |
| } | |
| func main() { | |
| var bi interface{} | |
| bi = &B{} | |
| t := reflect.TypeOf(bi).Elem() | |
| b := reflect.New(t) | |
| i, _ := b.Interface().(I) | |
| fmt.Println("----- invoke 'Method' via 'Call'. -----") | |
| i.Call() | |
| fmt.Println("----- invoke direct 'Method'. -----") | |
| i.Method(i) | |
| } | |
| /* | |
| ----- invoke 'Method' via 'Call'. ----- | |
| name: A | |
| <bool Value> | |
| ----- invoke direct 'Method'. ----- | |
| name: B | |
| <main.A Value> | |
| <int Value> | |
| <float32 Value> | |
| <bool Value> | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment