How do you swap two values? Provide a few examples.

Technology CommunityCategory: GolangHow do you swap two values? Provide a few examples.
VietMX Staff asked 3 years ago

Two values are swapped as easy as this:

a, b = b, a

To swap three values, we would write:

a, b, c = b, c, a

The swap operation in Go is guaranteed from side effects. The values to be assigned are guaranteed to be stored in temporary variables before starting the actual assigning, so the order of assignment does not matter.