Interactive Lesson:

Arrays and Slices

In Go, we can store simple and composite objects together in something called a slice.

We can instantiate slices using this [] syntax before the type. For example, we could define myAwesomeSlice which would be a slice of type int like so:

var myAwesomeSlice []int

Let’s take it slow, and have a look at how we can loop through all the items in our slice using the range built-in:

for index, item := range mySlice {
  fmt.Println(index)
  fmt.Println(item)
}

This returns 2 things, index which shows off the position in the slice, and item which is the value at that index.

Task

We want to test our new found knowledge of the range in built. You task, should you choose to accept it:

  • Use range to loop through all the items in the adventurers backpack.

Additional Scrolls of wisdom