This shot will teach us how to swap two variables in
We will start by declaring a variable using short 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
We have learned how to assign multiple variables. Now, we can use that feature to swap two variables in Golang:
variable1, variable2 = variable2, variable1
In the following example, we will try to swap two variables: x
and y
.
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)}
main()
function in Golang.x
and y
.x
and y
before swapping them.x
and y
after swapping them.