Pass Slice as Parameter to Function in Golang

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

package main

import "fmt"

func main() {

	a := [7]int{2, 4, -6, 8, -10, 24, 19}

	slice := a[:]

	fmt.Println("List of Elements")
	printSlice1(slice)

	fmt.Println("List of Elements")
	printSlice2(slice)

}

func printSlice1(slice []int) {
	for i := 0; i < len(slice); i++ {
		fmt.Printf("%d the element of a is %d\n", i, slice[i])
	}
}

func printSlice2(slice []int) {
	for index, value := range slice {
		fmt.Printf("%d the element of a is %d\n", index, value)
	}
}




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

List of Elements
0 the element of a is 2
1 the element of a is 4
2 the element of a is -6
3 the element of a is 8
4 the element of a is -10
5 the element of a is 24
6 the element of a is 19

List of Elements
0 the element of a is 2
1 the element of a is 4
2 the element of a is -6
3 the element of a is 8
4 the element of a is -10
5 the element of a is 24
6 the element of a is 19