On Sun, Nov 5, 2017 at 3:47 AM, <caffeinej...@gmail.com> wrote: > Hi, > > Newbie here. I am trying to understand the scope of variables in go - I ran > across an interesting situation and want to learn what is going on. Why do > these two functions yield different results: > https://play.golang.org/p/SyyWOY3fXz > > My understanding was that declaring myint either way in the function was the > same as far as scope is concerned - but obviously they are different > somehow. Do variables declared in the functions return section have a > larger scope or live longer? Or is something else going on here? Just > trying to understand what's going on.
In your first example you've got a variable called 'myint' that you're returning the value of, and then incrementing that variable in your defer. During return the value is being copied out of that variable and in to an unnamed variable that holds the return value of the function. In your second example you're naming the return variable, assigning a value to that return variable, copying the value of the variable back in to itself when returning and then incrementing that variable in your deferred function. Named return variables are often useful for this because they can be modified in defered functions that run after the return. https://golang.org/ref/spec#Return_statements - Jesse -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.