Created
March 8, 2015 19:45
-
-
Save saelo/4190b75724adc06b1c5a to your computer and use it in GitHub Desktop.
Decorators in Go
This file contains 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" | |
) | |
func Decorate(impl interface{}) interface{} { | |
fn := reflect.ValueOf(impl) | |
inner := func(in []reflect.Value) []reflect.Value { | |
f := reflect.ValueOf(impl) | |
fmt.Println("Stuff before") | |
// ... | |
ret := f.Call(in) | |
fmt.Println("Stuff after") | |
// ... | |
return ret | |
} | |
v := reflect.MakeFunc(fn.Type(), inner) | |
return v.Interface() | |
} | |
var Add = Decorate( | |
func (a, b int) int { | |
return a + b | |
}, | |
).(func(a, b int) int) | |
func main() { | |
fmt.Println(Add(1, 2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment