{

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


Golang Swap two numbers 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?

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, temporary (initial number1 variable value) value is assigned to number2 variable value.

Here temporary variable is declared and used to store the number1 value before doing swapping. number1 and number2 variable values are printed to 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 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?

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 console using 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.