Skip to content

Instantly share code, notes, and snippets.

@azhai
Forked from saelo/decorator.go
Created August 29, 2019 02:14
Show Gist options
  • Save azhai/ab1ab16199945da68e24f4c8c1b7f808 to your computer and use it in GitHub Desktop.
Save azhai/ab1ab16199945da68e24f4c8c1b7f808 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