On 18 dub, 15:44, Daniel Smith <
dan...@lukenine45.net> wrote:
> Suppose I have ret defined.
>
> var ret int
>
> I can do this, creating the new variable err:
>
> ret, err := SomethingThatCouldFail()
>
> However, this gives an error:
>
> var ret MyType
> ret.Field, err := SomethingThatCouldFail()
Here you are trying to (re)declare a variable named 'ret.Field'.
That's not a legal variable name:
http://golang.org/doc/go_spec.html#Short_variable_declarations
http://golang.org/doc/go_spec.html#Identifiers
>
> As does this:
>
> var ret [5]int
> ret[0], err := SomethingThatCouldFail()
Same story.
> Judging from the documentation [1], this is might be (it's unclear to me)
> the intended behavior, but it seems inconsistent to me. I'd expect all three
> or none to work.
>
> That's not so bad (just annoying), since it at least gives a compiler error.
> More insidious is this behavior:
>
> var ret int
> if SomeCondition {
> ret, err := SomethingThatCouldFail()
> if err != nil {
> return err
> }
>
> }
http://golang.org/doc/go_spec.html#Declarations_and_scope
"An identifier declared in a block may be redeclared in an inner
block. While the identifier of the inner declaration is in scope, it
denotes the entity declared by the inner declaration. "
> ret gets redeclared in the inner block, and the ret in the outer block never
> gets set. Again, it's hard to call this behavior wrong based on the spec,
> but it is easy to accidentally do this and it can make for hard-to-find bugs
> (especially the first time it happens to you). My preferred behavior would
> be for it to search enclosing scopes for "ret" as well as the current scope.
> I think that would be more user-friendly.
One doesn't have to (re)declare [local] variable names in a block.
Without that the problem can't demonstrate. Example:
var ret int
var err YourErrType
if SomeCondition {
ret, err = SomethingThatCouldFail() // note '=' instead of ':='
if err != nil {
return err
}
}
-bflm