Best way to swap variable values in Go?

Nicky Feller picture Nicky Feller · Jul 25, 2016 · Viewed 19k times · Source

Is it possible to swap elements like in python?

a,b = b,a

or do we have to use:

temp = a
a = b
b = temp

Answer

Sam Whited picture Sam Whited · Jul 25, 2016

Yes, it is possible. Assuming a and b have the same type, the example provided will work just fine. For example:

a, b := "second", "first"
fmt.Println(a, b) // Prints "second first"
b, a = a, b
fmt.Println(a, b) // Prints "first second"

Run sample on the playground

This is both legal and idiomatic, so there's no need to use an intermediary buffer.