Skip to content

Instantly share code, notes, and snippets.

@saelo
Created March 8, 2015 19:45
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save saelo/4190b75724adc06b1c5a to your computer and use it in GitHub Desktop.
Save saelo/4190b75724adc06b1c5a to your computer and use it in GitHub Desktop.
Decorators in Go
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