Arrays

An array contains other types in a fixed position. The position is given by an int.

Other as in some scripting languages, you have to “make room” for an array and define its size.

So this is not valid:

1 package main
2
3 func main() {
4         var names []string
5         names[0] = "hugo"
6         names[2] = "melc"
7 }

You would get an “index out of range [0] with length 0” error for line 5. This is because the array “names” in line for has no entries and no capacity for entries. As counting starts with “0”, the names[0] is out of range.

Strange, but true.

Valid:

package main

import "fmt"

func main() {
        var names [5]string
        names[0] = "hugo"
        names[2] = "melc"

        fmt.Println("My name is: " + names[0])
        fmt.Println("i dont know you,  " + names[1])
}

Initializing an array

You may initialize an array with values:

	x := [5]int{10, 20, 30, 40, 50} 

Loop though an array

With “for or range” you can loop through the array:

for i := 0; i < len(names); i++ {
        fmt.Println("Names ", i, ": ", names[i])
}

Index subparts of the array

With an index you can address subparts:

 fmt.Println("All names:", names)
 fmt.Println("Some names:", names[1:])

Here names[1:] gives you names index 1 and following.

This is not only possible with the beginning, but also the end:

fmt.Println("Some names:", names[:2])

Or both.

Array of string pointer

Often an array of pointers is used.

var namePointer [3]*string;
namePointer[0] = &names[0]
namePointer[1] = &names[2]

for i, aPointer := range namePointer {
   fmt.Println( i, " : ", aPointer)
}

Just keep in mind, that pointers just store memory addresses, so this output is:

0  :  0xc000076050
1  :  0xc000076070
2  :  <nil>

You see, that namePointer[2] is not initialized,m so its nil. That means it points into nowhere. This is not zero, its undefined.

To get the names out of the pointers we have to dereference them:

	for i, aPointer := range namePointer {
		fmt.Println( i, " : ", *aPointer)
	}

The problem with that is, that we there is no string at nil. So we get:

0  :  hugo
1  :  melc
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x108a532]

Always check for nil pointers

So your range looks like:

	for i, aPointer := range namePointer {
		if aPointer != nil{
			fmt.Println( i, " : ", *aPointer)
		}
	}

A more flexible array is the slice, lets go to that

See also