From d8e31920fbaf598e2e9f54c71554632ff5bbdcbe Mon Sep 17 00:00:00 2001 From: Francesc Campoy Date: Wed, 23 Jul 2014 13:42:34 +1000 Subject: [PATCH] go-tour: add defer slides LGTM=adg R=adg, campoy CC=golang-codereviews https://codereview.appspot.com/110520043 Committer: Andrew Gerrand --- content/flowcontrol.article | 20 ++++++++++++++++++++ content/prog/tour/defer-multi.go | 13 +++++++++++++ content/prog/tour/defer.go | 9 +++++++++ 3 files changed, 42 insertions(+) create mode 100644 content/prog/tour/defer-multi.go create mode 100644 content/prog/tour/defer.go diff --git a/content/flowcontrol.article b/content/flowcontrol.article index d910680..ef5fa59 100644 --- a/content/flowcontrol.article +++ b/content/flowcontrol.article @@ -108,6 +108,26 @@ This construct can be a clean way to write long if-then-else chains. .play prog/tour/switch-with-no-condition.go +* Defer + +A defer statement defers the execution of a function until the surrounding +function returns. + +The deferred call's arguments are evaluated immediately, but the function call +is not executed until the surrounding function returns. + +.play prog/tour/defer.go + +* Stacking defers + +Deferred function calls are pushed onto a stack. When a function returns, its +deferred calls are executed in last-in-first-out order. + +To learn more about defer statements read this +[[http://blog.golang.org/defer-panic-and-recover][blog post]]. + +.play prog/tour/defer-multi.go + * Congratulations! You finished this lesson! diff --git a/content/prog/tour/defer-multi.go b/content/prog/tour/defer-multi.go new file mode 100644 index 0000000..30af534 --- /dev/null +++ b/content/prog/tour/defer-multi.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + fmt.Println("counting") + + for i := 0; i < 10; i++ { + defer fmt.Println(i) + } + + fmt.Println("done") +} diff --git a/content/prog/tour/defer.go b/content/prog/tour/defer.go new file mode 100644 index 0000000..92cac76 --- /dev/null +++ b/content/prog/tour/defer.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + defer fmt.Println("world") + + fmt.Println("hello") +}