Pointer and Slice 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{5, 9, 1, 2, 8}
	p := &a

	fmt.Println("Element 0: ", (*p)[0])

	fmt.Println("List of Elements")
	for i := 0; i < len(a); i++ {
		fmt.Print((*p)[i], "  ")
	}

	fmt.Println("\nList of Elements")
	for index, value := range *p {
		fmt.Println(index, ": ", value)
	}

	fmt.Println("Elements of A array")
	ModifyArray(p)
	fmt.Println(a)
}

func ModifyArray(p *[]int) {
	(*p)[2] = 22
}




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

Element 0: 5
List of Elements
5  9  1  2  8
List of Elements
0: 5
1: 9
2: 1
3: 2
4: 8
Elements of A array
[5  9  22  2  8]