In-place swap using tuple assigment statement

62 Views Asked by At

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?

1

There are 1 best solutions below

2
hybridonroot On

The line *a, *b = *b, *a in the swap function swaps the values of a and b without using a temporary variable.

This evaluation involves the use of pointers in Go. When swap is called, it receives the memory addresses (pointers) of a and b. The line *a, *b = *b, *a dereferences these pointers, meaning it retrieves the values stored at the memory addresses pointed to by a and b.

Here's a step-by-step breakdown:

  1. *a retrieves the value stored at the memory address pointed to by a.
  2. *b retrieves the value stored at the memory address pointed to by b.
  3. *a, *b = *b, *a assigns the value of *b to *a and the value of *a to *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 a and b, effectively swapping their contents.