Lesson 16. Arrayed in splendor
After reading lesson 16, you’ll be able to
- Declare and initialize arrays
- Assign and access the elements of an array
- Iterate through arrays
Arrays are ordered collections of elements with a fixed length. This lesson uses arrays to store the names of planets and dwarf planets in our solar system, but you can collect anything you like.
Consider this
Do you have a collection or did you in the past? Maybe stamps, coins, stickers, books, shoes, trophies, movies, or something else?
Arrays are for collecting many of the same type of thing. What collections could you represent with an array?
Every element of an array has the same type. In this case, planets is an array of strings.
Individual elements of an array can be accessed by using square brackets [] with an index that begins at 0, as illustrated in figure 16.1 and shown in listing 16.1.
Listing 16.1. Array of planets: array.go
var planets [8]string planets[0] = "Mercury" #1 planets[1] = "Venus" planets[2] = "Earth" earth := planets[2] #2 fmt.Println(earth) #3
Even though only three planets have been assigned, the planets array has eight elements. The length of an array can be determined with the built-in len function. The other elements contain the zero value for their type, an empty string: