VarthanV

Go - Arrays Slices and Maps

Arrays

var (
    a [3]int
)

Arrays are pass by value and elements are copied

var (
    a = [3]int{0,0,0}
)

b := a // a gets copied to nb

Slices

    var []a int // nil,no storage
    var b = []int{1,2} // initialized
    a = append(a,3) // append to nil ok
    b = append(b,3)

    a = b // overwrites a
    e := a // same storage alias

    e[0] == b[0] //true
    

    var (
        d = [...]int{3,3,3} // length inferred as 3 , equal to no of elements present in the array
    )

Arrays vs Slice

SliceArray
Variable lengthLength fixed at compile time
Passed by referencePassed by value
Cannot be used as map keyCan be used as map key
Has copy and append helpers-
Useful as function parametersUseful as pseudo constants
Not comparable with ==Comparable with ==
    func foo(b []int){
        b[0] = 1 // modifies the orig passed value

        // To have a local copy
        c :=  make([]int ,len(b))
        copy(c , b) // dest ,source
    }

Maps

    var m map[string]int // nil no storage
    p := make(map[string]int) // non-nil but empty

    a := p["the"] // returns 0
    b := m["the"] // returns 0

    m["the"]+= 1 // panic nil map

    m = p
    m["and"]++ // OK , same as p now
    c := p["and"] // returns 1
p := map[string]int{} // non-nil but empty

a := p["foo"] // returns 0
b,ok := p["foo"] // 0, false

p["foo"]++

c, ok := p["foo"] // 1, true


if w, ok := p["foo"]; ok {
    // we know w is not default value
}

Builtins

functiontypeuse
len(s)stringstring length
len(a),cap(a)arrayarray length , capacity (constant)
make(T,x)sliceslice of type T with length x and capacity x
make(T,x,y)sliceslice of type T with length x and capacity y
copy(d,c)slicecopy from d c # min of two lengths
c= append(c,d)sliceappend d to c and return a new slice result
len(s) , cap(s)sliceslice length and capacity
make(T)mapmake map of type T
make(T,x)mapmake map of type T with hint for x elements
delete(m, k)mapdelete key k if present in m
len(m)maplength of m

nil

Many builtins are nil safe len,cap,range

    var s[]int
    var m map[string]int
    
    l := len(s) // length of slice s is zero

    i , ok := m["int"] // 0,false or missing key


    for _ , v := range s {
        // skip if is nil or empty
    }

    Make te zero value useful - Rob Pike
TypeValue
boolfalse
numbers0
string""
pointersnil
slicesnil
mapsnil
channelsnil
functionsnil
interfacesnil
    type Person struct {
        Age int
        Name string
        Friend []Person
    }

    var p Person // Person{0,"", nil}

nil pointer

slice

Kinds of nilDefinition
pointerspoint to nothing
sliceshave no backing array
mapsare not initialized
channelsare not initialized
functionsare not initialized
interfacesare not initialized

nil is useful