How to swap two variables in Go
This shot will teach us how to swap two variables in
We will start by declaring a variable using short variable declaration.
Variable declaration
We will initialize the variable while declaring it in the following syntax:
variable_name := value
We will declare and initialize multiple variables like this:
variable1, variable2 := value1, value2
In the same way, we can also reassign the multiple variables:
variable1, variable2 = value3, value4
Swap variables
We have learned how to assign multiple variables. Now, we can use that feature to swap two variables in Golang:
variable1, variable2 = variable2, variable1
Example
In the following example, we will try to swap two variables: x and y.
Code
package main//import format packageimport("fmt")//program execution starts herefunc main(){//declare and initialize multiple variablesx,y := 10,20//display variables before swapfmt.Println("Before swap : ", x, y)//swap the variablesx,y = y,x//display variables after swapfmt.Println("After swap : ", x, y)}
Code explanation
- Line 5: Import the format package.
- Line 9: Program execution starts from the
main()function in Golang. - Line 12: Declare and initialize the variables
xandy. - Line 15: Display the variables
xandybefore swapping them. - Line 18: Swap the variables, using the multiple variable assignments.
- Line 21: Display the variables
xandyafter swapping them.