Arrays
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
As always, arrays start a position zero. They are also fixed in size, the length cannot be modified once an array is declared. For more flexibility see slices in the next section.
Initialize array#
Define an array declaring the number of elements and the data element, for example:
var myArray [5]intIf you print this out as-is, Go will initialize each element to zero:
package main
import "fmt"
func main() {
var myArray [5]int
fmt.Println(myArray)
}go run .[0 0 0 0 0]Populating array#
You can define the initial values using the following syntax, remember we can omit the var syntax and use colon/equals :=:
package main
import "fmt"
func main() {
myArray := [5]int{1976, 2024, 1992, 1986, 2004}
fmt.Println(myArray)
}Accessing array#
You can access a specific element within an array, for example to print the first element:
package main
import "fmt"
func main() {
myArray := [5]int{1976, 2024, 1992, 1986, 2004}
fmt.Println(myArray[0])
}Modify array#
Likewise, you can modify the value of an element:
package main
import "fmt"
func main() {
myArray := [5]int{1976, 2024, 1992, 1986, 2004}
fmt.Println(myArray[1])
myArray[1] = 1066
fmt.Println(myArray[1])
}Length of array#
To determine the length of an array:
package main
import "fmt"
func main() {
myArray := [5]int{1976, 2024, 1992, 1986, 2004}
fmt.Println(len(myArray))
}Copy Array#
Understand the behavior when making copies of arrays.
package main
import "fmt"
func main() {
myArray := [5]string{"dog", "cat", "rabbit", "duck", "mouse"}
fmt.Println(myArray)
animals := myArray
fmt.Println(animals)
}If you make changes to either myArray or animals there are now independent arrays, one dose not effect the other.
package main
import "fmt"
func main() {
myArray := [5]string{"dog", "cat", "rabbit", "duck", "mouse"}
animals := myArray
myArray[0] = "lizard"
animals[0] = "snail"
fmt.Println(myArray)
fmt.Println(animals)
}Output:
[lizard cat rabbit duck mouse]
[snail cat rabbit duck mouse]Compare#
You can compare all data types in Go. When comparing arrays, the data type must match, for example you can’t compare an array of integers against and array of strings or else you’ll get a compile error.
The following example with print out true then false:
package main
import "fmt"
func main() {
myArray := [5]string{"dog", "cat", "rabbit", "duck", "mouse"}
animals := myArray
myBool := myArray == animals
fmt.Println(myBool)
animals[0] = "snail"
myBool = myArray == animals
fmt.Println(myBool)
}