mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-25 10:25:23 +00:00
Merge pull request #660 from szaydel/master
Learn function decorators with Go
This commit is contained in:
commit
f97481c6b1
@ -196,6 +196,21 @@ love:
|
|||||||
learnInterfaces() // Good stuff coming up!
|
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) {
|
func learnDefer() (ok bool) {
|
||||||
// Deferred statements are executed just before the function returns.
|
// Deferred statements are executed just before the function returns.
|
||||||
defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
|
defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
|
||||||
|
Loading…
Reference in New Issue
Block a user