govariable-assignmentshorthandmultiple-variable-return

Go: multiple variable short declaration statement with a multiple-return value function


Is it possible to declare multiple variables at once with a multiple return value function call?

I want to use it in for loop multiple variable initialization statement but can't find a way to do this in Go.

For example, this code snippet work:

x := "foo"
y, z := fmt.Print("bar")

However, when I try to use short declaration syntax x, y := "value1", "value2" it fails:

x, y, z := "foo", fmt.Print("bar")

As I understood, the compiler tries to assign both return values of a function to the second variable y.

Please advise is this a possible case in Golang, or what alternatives I can use in for loop initialization statement.


Solution

  • Please advise is this a possible case in Golang

    No, it's not possible.


    As per the official language spec, it is not allowed to combine multi-valued expressions with other multi-or-single-valued expressions in an assignment. The section on Assignment Statements says:

    There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call ... In the second form, the number of operands on the left must equal the number of expressions on the right, each of which MUST be single-valued.

    And short variable declaration is a shorthand of regular variable declaration which follows the rules of assignment statements quoted above.


    what alternatives I can use in for loop initialization statement.

    You could wrap the two statements into a custom function that returns 3 values and use that function in the for loop's InitStmt. For example:

    func f() (string, int, error) {
        x := "foo"
        y, z := fmt.Print("bar")
        return x, y, z
    }
    
    for x, y, z := f(); ... {
        // ...
    }