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"
Run sample on the playground
This is both legal and idiomatic, so there's no need to use an intermediary buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With