Created
January 13, 2015 00:12
-
-
Save jaehue/b5742aaba47088bbb02b to your computer and use it in GitHub Desktop.
Golang Function Invoker
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 Command struct { | |
| Func interface{} | |
| Args []interface{} | |
| Result []interface{} | |
| Done chan bool | |
| } | |
| func sum(a, b int) int { | |
| fmt.Printf("[sum] %d + %d = %d\n", a, b, a+b) | |
| return a + b | |
| } | |
| func main() { | |
| c := Command{ | |
| Func: sum, | |
| Args: []interface{}{1, 2}, | |
| Done: make(chan bool), | |
| } | |
| c.invoke() | |
| <-c.Done | |
| fmt.Printf("Result: %v", c.Result) | |
| } | |
| func (c *Command) invoke() { | |
| go func() { | |
| f := reflect.ValueOf(c.Func) | |
| var in []reflect.Value | |
| for _, v := range c.Args { | |
| in = append(in, reflect.ValueOf(v)) | |
| } | |
| fmt.Println("Call Command Function") | |
| results := f.Call(in) | |
| fmt.Println("Complete Command Function.") | |
| var returns []interface{} | |
| for _, v := range results { | |
| returns = append(returns, v.Interface()) | |
| } | |
| c.Result = returns | |
| c.Done <- true | |
| }() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment