How to swap two variables in Go

This shot will teach us how to swap two variables in Goalso known as Golang.

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 package
import(
"fmt"
)
//program execution starts here
func main(){
//declare and initialize multiple variables
x,y := 10,20
//display variables before swap
fmt.Println("Before swap : ", x, y)
//swap the variables
x,y = y,x
//display variables after swap
fmt.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 x and y.
  • Line 15: Display the variables x and y before swapping them.
  • Line 18: Swap the variables, using the multiple variable assignments.
  • Line 21: Display the variables x and y after swapping them.