2. Slices in Go

99 times out of 100 you will use a slice instead of an array when working with ordered lists.

Arrays are fixed in size. Once you make an array like [ 10]int you can't add an 11th element.

A slice is a dynamically-sized, flexible view of the elements of an array.

The zero value of slice is nil.arrow-up-right

Non-nil slices always have an underlying array, though it isn't always specified explicitly. To explicitly create a slice on top of an array we can do:

primes := [6]int{2, 3, 5, 7, 11, 13}
mySlice := primes[1:4]
// mySlice = {3, 5, 7}

The syntax is:

arrayname[lowIndex:highIndex]
arrayname[lowIndex:]
arrayname[:highIndex]
arrayname[:]

Where lowIndex is inclusive and highIndex is exclusive.

lowIndex, highIndex, or both can be omitted to use the entire array on that side of the colon.

Creating Empty Slices

result := []Message{}

This creates an empty slice of type Message.

Breaking It Down Piece by Piece

1

Part 1: result :=

  • Creates a new variable called result

  • := means "declare and initialize" (Go figures out the type automatically)

2

Part 2: []Message

  • Message is the type of elements the slice will hold

  • [] means it's a slice (dynamic array)

3

Part 3: {}

  • The empty braces mean "start with zero elements"

Assignment

Retries are a premium feature now! Textio's free users only get 1 retry message, while pro members get an unlimited amount.

Complete the getMessageWithRetriesForPlan function. It takes a plan variable as input as well as an array of 3 messages. You've been provided with constants representing the plan types at the top of the file.

Solution

Explanation

Arrays vs Slices

  • messages is an array: [3]string

  • The function returns a slice: []string

  • Arrays must be sliced before returning

Examples:

Slice Indexing Rules

  • Start index is inclusive

  • End index is exclusive

messages[:2] // indexes 0 and 1

Error Handling Pattern

  • On error:

    • Return nil for the slice

    • Return a constructed error value

Example:

return nil, errors.New("unsupported plan")

A nil slice is valid and idiomatic in Go.