2 ways to find swap two numbers/variables in Golang Example

In this article, you are about to learn two ways to swap two numbers or variables in Go language.

The first method is to swap variables in a temporary variable, while the second alternative is not to use a temporary variable.

How to Swap two numbers using a temporary variable Golang?

Two variables number1 and number2 are declared and assigned with 12 and 30 values respectively.

Here is a sequence of steps for swapping numbers

  • First, the number1 variable value is assigned to a temporary variable
  • Next, the number2 variable value is assigned to the number1 variable
  • Finally, the temporary (initial number1 variable value) value is assigned to the number2 variable value.

Here temporary variable is declared and used to store the number1 value before swapping. number1 and number2 variable values are printed to the console before and after the swapping process using the Println function.

package main

import (
    "fmt"
)

func main() {
    number1, number2: = 12, 30
    fmt.Println("Before Swap process")
    fmt.Println("Number1:", number1)
    fmt.Println("Number2:", number2)

    // number1 is assigned to a temporary variable
    temporary: = number1
        // number1 is assigned to number2 variable
    number1 = number2
        //  temporary  is assigned to number2
    number2 = temporary

    fmt.Println("After Swap process")
    fmt.Println("Number1:", number1)
    fmt.Println("Number2:", number2)
}

The above program is compiled and executed, Output is

Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12

How to Swap two numbers without using a temporary variable Golang?

In this program, Numbers are swapped without using a temporary variable.

Here, tuple assignments are used to swap the numbers. Swapped numbers a reprinted to the console using the println function.

Here is a program swap number using the tuple assignment.

package main

import (
    "fmt"
)

func main() {
    number1, number2: = 12, 30
    fmt.Println("Before Swap process")
    fmt.Println("Number1:", number1)
    fmt.Println("Number2:", number2)
    number1, number2 = number2, number1

    fmt.Println("After Swap process")
    fmt.Println("Number1:", number1)
    fmt.Println("Number2:", number2)
}

Output:

Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12

Conclusion

To conclude, there is no performance difference; you can use any approach based on your preferences.