2

How do you assign a struct field variable in a multiple assignment statement? Please refer to code below.

type TestMultipleReturns struct {
    value string
}

func (t *TestMultipleReturns) TestSomething() {
    someMap := make(map[string]string)
    someMap["Test"] = "world"
    t.value, exists := someMap["doesnotexist"] // fails

    // works, but do I really need a 2nd line?
    tmp, exists := someMap["doesnotexist"] 
    t.value = tmp

    if exists == false {
        fmt.Println("t.value is not set.")
    } else {
        fmt.Println(t.value)
    }
}

1 Answer 1

6

Short variable declaration do not support assigning struct receiver properties; they are omitted from the spec definition:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new.

The fix is to define exists before the assignment and not use short variable declarations:

type TestMultipleReturns struct {
    value string
}

func (t *TestMultipleReturns) TestSomething() {
    someMap := make(map[string]string)
    someMap["Test"] = "world"
    var exists bool
    t.value, exists = someMap["doesnotexist"]

    if exists == false {
        fmt.Println("t.value is not set.")
    } else {
        fmt.Println(t.value)
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, though it is still 2 lines. This seems inconsistent with the behavior where you can have 1 variable already defined and 1 variable not defined in undefined, defined := MultipleReturnCall(). Quirks of Go!
@PressingOnAlways: If you think this was just an oversight by the spec authors, I would encourage you to submit a proposal for the change.
I'm just happy it doesn't require 3 lines!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.