-
-
Save smallnest/92849687ffeb77c82723e01fec8b10e4 to your computer and use it in GitHub Desktop.
Decorators in Go
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" | |
) | |
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