Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Go Arrays & Slices

Go Arrays & Slices

An overview of how slices and arrays work in Go.

Nathan Youngman

May 25, 2015
Tweet

More Decks by Nathan Youngman

Other Decks in Programming

Transcript

  1. Arrays are fixed-length planets := [8]string{
 "Mercury",
 "Venus",
 "Earth",
 "Mars",


    "Jupiter",
 "Saturn",
 "Uranus",
 "Neptune",
 } 0 1 2 3 4 5 6 7
  2. Arrays are values planetBackup := planets
 
 // make way

    for an interstellar bypass
 planets[2] = “" fmt.Println(planets) // [Mercury Venus Mars Jupiter Saturn Uranus Neptune]
 
 fmt.Println(planetBackup) // [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune]
  3. Slicing makes a window terrestrial := planets[0:4]
 gasGiants := planets[4:6]


    iceGiants := planets[6:8] 0 1 2 3 4 5 6 7 terrestrial gasGiants iceGiants
  4. Making a slice // allPlanets := planets[:] planets := []string{


    "Mercury",
 "Venus",
 "Earth",
 "Mars",
 "Jupiter",
 "Saturn",
 "Uranus",
 "Neptune",
 }
  5. Append to slices planets = append(planets, "Pluto") 0 1 2

    3 4 5 6 7 8 9 10 11 12 13 14 15 fmt.Println(len(planets), cap(planets)) // 9 16