Go Program of 2 Ways to Find Swap Two Numbers and Variables

Go Program of 2 Ways to Find Swap Two Numbers and Variables. In this program, This covers 2 ways to swap two numbers or variables in Golang. The first one is to swap variables in a temporary variable, another one is not using a temporary variable.

Go Program of 2 Ways to Find Swap Two Numbers and Variables

Method=1 Swap two values/numbers using a temporary variable

Source Code

package main

import (
 "fmt"
)

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

 // number1 is assigned to 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)
}

Output

Example =2 swap numbers without a temporary variable

Source Code

package main

import (
 "fmt"
)

func main() {
 number1, number2 := 18, 34
 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