FAQ
Hi

The following code demonstrates an issue I ran into recently:
http://play.golang.org/p/tXYJtlw-lg

The first line in the main function is creating a new variable in that
scope which shadows the global variable. This means that any changes I make
are not reflected in the other go routine since it points at the global
variable.

This was very confusing and took me a long time to track down. The reason I
have the := and not = on that line is because I AM creating a new error
variable.. I assumed the error variable would be created and the struct
variable would just be updated.

Just thought I would point it out and it's the first time go has done
something unexpected for me.

Ryan



--

Search Discussions

  • Jan Mercl at Nov 10, 2012 at 3:25 pm

    On Sat, Nov 10, 2012 at 4:08 PM, Ryan Slade wrote:
    This was very confusing and took me a long time to track down. The reason I
    have the := and not = on that line is because I AM creating a new error
    variable.. I assumed the error variable would be created and the struct
    variable would just be updated.
    IOW, you have assumed that it is not possible to have a short variable
    declaration with a name already "taken" in outer/global scope. Now,
    that's what I would call unexpected.

    -j

    --
  • Maxim Khitrov at Nov 10, 2012 at 3:28 pm

    On Sat, Nov 10, 2012 at 10:08 AM, Ryan Slade wrote:
    Hi

    The following code demonstrates an issue I ran into recently:
    http://play.golang.org/p/tXYJtlw-lg

    The first line in the main function is creating a new variable in that scope
    which shadows the global variable. This means that any changes I make are
    not reflected in the other go routine since it points at the global
    variable.

    This was very confusing and took me a long time to track down. The reason I
    have the := and not = on that line is because I AM creating a new error
    variable.. I assumed the error variable would be created and the struct
    variable would just be updated.

    Just thought I would point it out and it's the first time go has done
    something unexpected for me.

    Ryan
    Relevant language spec section:

    http://golang.org/ref/spec#Short_variable_declarations

    "a short variable declaration may redeclare variables provided they
    were originally declared in the same block with the same type, and at
    least one of the non-blank variables is new."

    In this case, the original s is in a different block, so it can't be redeclared.

    - Max

    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedNov 10, '12 at 3:08p
activeNov 10, '12 at 3:28p
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase