Tuesday, January 5, 2021

Tuple Assignments in Go

Learn about tuple assignments in Go and how to use it.

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:

i, j, k := 2, 3, 4

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:

x, y = y, x

And you could also run operations as needed. For example:

x, y = y, x*2

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:

f, err := os.Open("file.txt")

Similarly, you may be familiar with a similar pattern when using channels:

v, ok = <-ch

Or doing type assertion:

v, ok = x.(T)

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 languageTuple 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.

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Pointers in Go

Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

Popular Posts