go - Defer usage clarification -


let's assume have following function

func printnumbers(){  var x int   defer fmt.println(x)   := 0; < 5; i++{   x++  } } 

as said in specification:

each time "defer" statement executes, function value , parameters call evaluated usual , saved anew actual function not invoked.

obviously, 0 printed out when function execution ends. should if want print out final value of variable x?

i've come following solution:

func printnumbers(){   var x int    printval := func(){     fmt.println(x)   }    defer printval()    := 0; < 5; i++{     x++   } } 

so wonder if there better way resolve problem.

if defer has arguments evaluated @ line of defer-statement; illustrated in following snippet, defer print 0:

func printnumber() {    := 0    defer fmt.println(i) // print 0    i++    return } 

you can use anonymous function defer statement if want postpone execution of statement or function until end of enclosing (calling) function. here updated example:

func printnumbers() {     x := 0     defer func() { fmt.println(x) }()     i:=0; < 5; i++ {         x++;     }     return } 

http://play.golang.org/p/yqgq_8a0_9


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -