Categories
Data Structure and Algorithm My Go Tutorial

Array, for, for..range, len(), function(call by value)

an ordered sequence of elements of the same type and access to an element by index begins with zero for the first element.

var arr = [5]int {1,2,4,5,6}
var i int
for i=0; i< len(arr); i++ {
    fmt.Println("printing elements ",arr[i]
}
var value int
for i, value = range arr{
    fmt.Println(" range ",value)
}
for _, value = range arr{
    fmt.Println("blank range",value)
}
package main

import "fmt"

//twiceValue method given array of int type
func twiceValue(arr [5]int) {
	for i, value := range arr {
		arr[i] = 2 * value
	}
}

func main() {
	var arr = [5]int{1, 2, 3, 4, 5, 6}
	// pass by value when twiceValue function called
	twiceValue(arr)

	for i := 0; i < len(arr); i++ {
		// Original array value unmodifed () twiceValue function
		fmt.Println("new slice value", arr[i])
	}
}

https://play.golang.org/p/-DRHLqWWB66

Go arrays are not dynamic but have a fixed size. To add more elements than the size, a bigger array needs to be created and all the elements of the old one need to be copied. An array is passed as a value through functions by copying the array. Passing a big array to a function might be a performance issue.