In this tutorial, we will learn how to swap two numbers in Go. We will cover two methods: using a temporary variable and using multiple assignment to swap the values of two variables.
Swapping refers to the process of exchanging the values of two variables. This can be useful in various programming scenarios where the order or value of variables needs to be interchanged.
The syntax to swap two numbers in Go can be done in two ways:
// Using a temporary variable
func swapWithTemp(a, b int) (int, int) {
temp := a
a = b
b = temp
return a, b
}
// Using multiple assignment
func swapWithMultipleAssignment(a, b int) (int, int) {
a, b = b, a
return a, b
}
We can use a temporary variable to swap the values of two variables.
For example,
swapWithTemp
that takes two parameters a
and b
of type int
.temp
to hold the value of a
.b
to a
.temp
(original value of a
) to b
.a
and b
.swapWithTemp
function with sample values and print the result.package main
import (
"fmt"
)
func swapWithTemp(a, b int) (int, int) {
temp := a
a = b
b = temp
return a, b
}
func main() {
a, b := 5, 10
fmt.Printf("Before swapping: a = %d, b = %d\n", a, b)
a, b = swapWithTemp(a, b)
fmt.Printf("After swapping with temp variable: a = %d, b = %d\n", a, b)
}
Before swapping: a = 5, b = 10 After swapping with temp variable: a = 10, b = 5
We can use multiple assignment to swap the values of two variables in a single line.
For example,
swapWithMultipleAssignment
that takes two parameters a
and b
of type int
.a
and b
in a single line.a
and b
.swapWithMultipleAssignment
function with sample values and print the result.package main
import (
"fmt"
)
func swapWithMultipleAssignment(a, b int) (int, int) {
a, b = b, a
return a, b
}
func main() {
a, b := 5, 10
fmt.Printf("Before swapping: a = %d, b = %d\n", a, b)
a, b = swapWithMultipleAssignment(a, b)
fmt.Printf("After swapping with multiple assignment: a = %d, b = %d\n", a, b)
}
Before swapping: a = 5, b = 10 After swapping with multiple assignment: a = 10, b = 5