Apart from the standard way to declare variables, Go offers another way known as tuple assignment. Tuple assignments allow declaring (and assigning) several variables at the same time with the caveat that the expressions on the right are evaluated before any of the variables are updated.
Since tuple assignments are very frequently used in Go, let's see some ways to use it effectively.
Quicker initialization
The first obvious use of tuple assignment is to declare and assign multiple variables at once. The benefits are more readability and less verbosiness. For example:
Variable Swap
Variable swaps are significantly clearer in Go due to this feature. For example, here's how one would swap the values of x an y in Go:
And you could also run operations as needed. For example:
Multiple returned values
Another common use is to capture values returned from a function that returns multiple results. For example, a call to os.Open:
Similarly, you may be familiar with a similar pattern when using channels:
Or doing type assertion:
Conclusion
On this article we learned about tuple assignments in Go, which apart from the standard way to declare variables, is a very common pattern used in the language. Tuple assignments allow declaring (and assigning) several variables at the same time with the caveat that the expressions on the right are evaluated before any of the variables are updated.