Paul Artman
Paul Artman

Reputation: 34

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.

Upvotes: 0

Views: 290

Answers (2)

mkopriva
mkopriva

Reputation: 38333

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(); ... {
    // ...
}

Upvotes: 4

Set Kyar Wa Lar
Set Kyar Wa Lar

Reputation: 4644

Base on the documentation, fmt.Print is returning 2 values. So, you can't assign something like that.

The following is the documentation enter image description here

The following one work because you are assigning 2 values return from fmt.Print.

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

Upvotes: 1

Related Questions