funcgenSumFunc()(func(int)int, func(int)int) { var sum int
add := func(num int)int { sum = sum + num return sum } sub := func(num int)int { sum = sum - num return sum } return add, sub }
funcmain() { f1, f2 := genSumFunc() g1, g2 := genSumFunc() var res int res = f1(1) // 1 res = f1(1) // 2 res = f2(1) // 1 res = g1(1) // 1 res = g1(1) // 2 res = g2(1) // 1 }
var sum int funcgenSumFunc()(func(int)int, func(int)int) { add := func(num int)int { sum = sum + num return sum } sub := func(num int)int { sum = sum - num return sum } return add, sub }
funcmain() { f1, f2 := genSumFunc() g1, g2 := genSumFunc() var res int res = f1(1) // 1 res = f1(1) // 2 res = f2(1) // 1 res = g1(1) // 2 res = g1(1) // 3 res = g2(1) // 2 }
defsome_decorator_without_params(fn): @functools.wraps(fn) defwrapper(*args, **kwargs): # do something before function fn(*args, **kwargs) # do something after function return wrapper
defsome_decorator_with_params(params): defdecorator(fn): @functools.wraps(fn) defwrapper(*args, **kwargs): # do something before function using params fn(*args, **kwargs) # do something after function using params return wrapper return decorator
@some_decorator_without_params @some_decorator_with_params(params) defHelloWorld(who, when="now"): print("Hello World to %s at %s!" % (who, when))
type Decorator func(http.HandlerFunc)http.HandlerFunc
funcSomeDecorator(h http.HandlerFunc)http.HandlerFunc { returnfunc(w http.ResponseWriter, r *http.Request) { // do something before handler h(w,r) // do something after handler } }
funcMiddlewares(h http.HandlerFunc, decos ...Decorator)http.HandlerFunc { for deco := range decos { d := decos[len(decos)-1-deco] h = d(h) } return h }
funcHelloWorldHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf("Hello World!") return }