Pass Pointer to Functions in Golang

Create new folder named src. In src folder, create new file named main.go as below:

package main

import "fmt"

func main() {
	var a int = 1
	ChangeValue1(a)
	fmt.Println("a:", a)
	ChangeValue2(&a)
	fmt.Println("a:", a)

	b, c := 3, 4
	p, q := &b, &c
	Swap1(b, c)
	fmt.Println("b:", b, ", c:", c)
	Swap2(p, q)
	fmt.Println("b:", b, ", c:", c)
}

func ChangeValue1(a int) {
	a = 2
}

func ChangeValue2(p *int) {
	*p = 2
}

func Swap1(a, b int) {
	temp := a
	a = b
	b = temp
}

func Swap2(p, q *int) {
	temp := *p
	*p = *q
	*q = temp
}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

a: 1
a: 2
b: 3 , c: 4
b: 4 , c: 3