In-place swap is a technique, which is used to swap a content of two distinct variables without any temporary storage variable.
GoLang Spec mentions: A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables.
Below code performs swap operation without using temporary variable(as per syntax):
package main
import "fmt"
func main() {
a, b := 1, 2
swapActual(&a, &b)
fmt.Println(a, b)
a, b = 1, 2
swapCopy(a, b)
}
func swapActual(a, b *int) {
*a, *b = *b, *a
}
func swapCopy(a, b int) {
a, b = b, a
fmt.Println(a, b)
}
What is the mechanics behind evaluation of tuple assignment statement *a, *b = *b, *a? Does this evaluation involve temporary storage, implicitly?
The line
*a, *b = *b, *ain theswapfunction swaps the values ofaandbwithout using a temporary variable.This evaluation involves the use of pointers in Go. When
swapis called, it receives the memory addresses (pointers) ofaandb. The line*a, *b = *b, *adereferences these pointers, meaning it retrieves the values stored at the memory addresses pointed to byaandb.Here's a step-by-step breakdown:
*aretrieves the value stored at the memory address pointed to bya.*bretrieves the value stored at the memory address pointed to byb.*a, *b = *b, *aassigns the value of*bto*aand the value of*ato*b.This evaluation doesn't involve temporary storage within the context of the user's code. It directly exchanges the values at the memory locations pointed to by
aandb, effectively swapping their contents.