diff options
author | Levi Bostian <levi.bostian@gmail.com> | 2014-06-29 17:29:18 -0500 |
---|---|---|
committer | Levi Bostian <levi.bostian@gmail.com> | 2014-06-29 17:29:18 -0500 |
commit | f97481c6b156bffc47143a1c74d21669ac1f3ee5 (patch) | |
tree | e35d3873b9b840530fdecae46597387dec36e28c | |
parent | 17a1303e37190573fee767c02bd4f87bb70783cf (diff) | |
parent | 8b6920a70a6f52657bf59a20a4120af98e4187fe (diff) |
Merge pull request #660 from szaydel/master
Learn function decorators with Go
-rw-r--r-- | go.html.markdown | 19 |
1 files changed, 17 insertions, 2 deletions
diff --git a/go.html.markdown b/go.html.markdown index c70f96bd..a9a7de72 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -116,10 +116,10 @@ can include line breaks.` // Same string type. learnFlowControl() // Back in the flow. } -// It is possible, unlike in many other languages for functions in go +// It is possible, unlike in many other languages for functions in go // to have named return values. // Assigning a name to the type being returned in the function declaration line -// allows us to easily return from multiple points in a function as well as to +// allows us to easily return from multiple points in a function as well as to // only use the return keyword, without anything further. func learnNamedReturns(x, y int) (z int) { z = x * y @@ -196,6 +196,21 @@ love: learnInterfaces() // Good stuff coming up! } +// Decorators are common in other languages. Same can be done in Go +// with function literals that accept arguments. +func learnFunctionFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } +} + +// Next two are equivalent, with second being more practical +fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!")) + +d := learnFunctionFactory("summer") +fmt.Println(d("A beautiful", "day!")) +fmt.Println(d("A lazy", "afternoon!")) + func learnDefer() (ok bool) { // Deferred statements are executed just before the function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") |