Lesson 17. Slices: windows into arrays

 

After reading lesson 17, you’ll be able to

  • Use slices to view the solar system through a window
  • Alphabetize slices with the standard library

The planets in our solar system are classified as terrestrial, gas giants, and ice giants, as shown in figure 17.1. You can focus on the terrestrial ones by slicing the first four elements of the planets array with planets[0:4]. Slicing doesn’t alter the planets array. It just creates a window or view into the array. This view is a type called a slice.

Figure 17.1. Slicing the solar system
Consider this

If you have a collection, is it organized in a certain way? The books on a library shelf may be ordered by the last name of the author, for example. This arrangement allows you to focus in on other books they wrote.

You can use slices to zero in on part of a collection in the same way.

17.1. Slicing an array

Slicing is expressed with a half-open range. For example, in the following listing, planets[0:4] begins with the planet at index 0 and continues up to, but not including, the planet at index 4.

Listing 17.1. Slicing an array: slicing.go
planets := [...]string{
    "Mercury",
    "Venus",
    "Earth",
    "Mars",
    "Jupiter",
    "Saturn",
    "Uranus",
    "Neptune",
}

terrestrial := planets[0:4]
gasGiants := planets[4:6]
iceGiants := planets[6:8]

fmt.Println(terrestrial, gasGiants, iceGiants)            #1

17.2. Composite literals for slices

17.3. The power of slices

17.4. Slices with methods

Summary