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
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"
This is both legal and idiomatic, so there's no need to use an intermediary buffer.