Arrays, Slice & Maps

/*ARRAY & SLICES*/


-->Slice refers to underlying array.
--> Built in function cap() return capacity. (eg prog2)
-->Built in function len() can be used to find the length of array and slice (eg prog1)
-->Make function can be used to create slice.(eg prog 1)

PROGRAM 1
package main

import "fmt"

func main() {
var ar [4]int //size is a part of type
var b =[]int {1,2,3,4,5} /*Slice literals look like array literals .
this creates an array of length 5 and then creat
a slice to refer it*/
e:=len(ar) //built in function len() reports size of array n slice
var c=[4]int{1,2} //array of size 4 with first two non zero.
var d=[...]int{1,2,3,4} //Dont want to count, use [...]
g:=[10]int {2:4,4:5,1:15} /*Don't want to initialize them all? use "KEY:VALUE" pair*/

/*make is used to allocate slice. it is also used for maps and channels*/
/* why make not new? Because we need to make a slice, not just allocate the memory. make([]int) returns []int while new([]int) returns *[]int*/

var s100=make([]int,100) // slice:100 ints

f(ar) /*arrays are values, not implicit pointers as in C. You can take array's address*/
f2(&ar)
fmt.Print(b,"\n")
fmt.Print(c,"\n")
fmt.Print(d,"\n")
fmt.Print(e,"\n")
fmt.Print(g,"\n")
fmt.Print(s100,"\n")
}

func f(a [4]int) {
fmt.Print("function f",a,"\n")
}

func f2(a *[4]int) {
fmt.Print("function f2",a,"\n")
}

OUTPUT OF PROGRAM 1

function f[0 0 0 0]
function f2&[0 0 0 0]
[1 2 3 4 5]
[1 2 0 0]
[1 2 3 4]
4
[0 15 4 0 5 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]