Hello everyone, In this post, we will show you how to swap two numbers in the Go programming language. The example program has been tested and shared in the same post.

Go – Swap two numbers

In below program, you can see it has two functions defined, the swap() function is taking two integers as an argument and which is responsible for swapping given two number and main() function is an entry point of an application.

package main
import "fmt"
// main function
func main() {
swap(10, 20)
// function to swap two number
func swap(a int, b int) {
fmt.Println("Before: a = ", a, "b = ", b)
// swapping logic
a = a + b
b = a - b
a = a - b
fmt.Println("After: a = ", a, "b = ", b)


Before: a =  10 b =  20
After: a =  20 b =  10


  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *