From 3919cfa894789b3f4829bfff737094970643e125 Mon Sep 17 00:00:00 2001 From: "jian.han" Date: Fri, 12 Jan 2018 15:08:16 +1000 Subject: [PATCH] added block example --- defer/main.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/defer/main.go b/defer/main.go index a84f1da..25ccbc9 100644 --- a/defer/main.go +++ b/defer/main.go @@ -23,7 +23,19 @@ func deferInsideLoop() { } } +// The deferred func above will only run when the func ends not when the deferred func’s surrounding block ends +// (the area inside curly braces containing the defer call). As seen in the example code, you can create separate blocks just using curly braces. +func block() { + { + defer func() { + fmt.Println("block: defer runs") + }() + } + fmt.Println("main: ends") +} + func main() { // nilFuncDefer() - deferInsideLoop() + // deferInsideLoop() + block() }