Slices

Question Click to View Answer

What does the following code print?

evens := []int{2, 4}
fmt.Println(evens)

[2 4] is printed.

The slice type is an abstraction that's built on top of the array type.

[2]int{2, 4} creates an array whereas []int{2, 4} creates a slice.

What does the following code print?

numbers := []int{55, 77, 99, 11, 88}
fmt.Println(numbers[1:4])

[77 99 11] is printed.

numbers[1:4] takes the second, third, and fourth elements from the numbers slice.

What does the following code print?

numbers := []int{55, 77, 99, 11, 88}
fmt.Println(numbers[2:])

[99 11 88] is printed.

numbers[2:] starts at the third element of the slice and takes all the remaining elements. It's equivalent to numbers[2:len(numbers)].

What does the following code print?

numbers := []int{55, 77, 99, 11, 88}
fmt.Println(numbers[:3])

[55 77 99] is printed.

numbers[:3] starts at the first element in the slice and takes all elements up to the third element. It's the same as numbers[0:3].

What does the following code print?

letters := []string{"a", "b", "c"}
fmt.Println(len(letters))

3 is printed.

The letters slice has a length of three.

What does the following code print?

words := make([]string, 8)
words[0] = "hi"
words[1] = "the"
fmt.Println(len(words))

8 is printed.

The words slice is declared to contain string values and have a length of 8. We only added two values to the words slice, but it still has a length of 8 (the other 6 values are the zero string values).

What does the following code print?

hairColors := []string{"blue", "blonde"}
more := append(hairColors, "brown")
fmt.Println(more)

[blue blonde brown] is printed.

The hairColors slice contains two strings.

The append() function creates a new slice that has all the elements from the hairColors slice, plus brown.

The hairColors slice has a length of two and there isn't room for additional elements to be added - that's why append() creates a new slice in this example.

What does the following code print?

var odds = []int{1, 3}
var evens = []int{8, 10}
fmt.Println(append(odds, evens...))

[1 3 8 10] is printed.

The append() function can also be used to concatenate two slices.

append() is a variadic function - these functions will be covered in greater detail in future quizzes.

What does the following code print?

var letters = []string{"a", "b", "c"}
var someLetters = make([]string, 2)
copy(someLetters, letters)
fmt.Println(someLetters)

[a b] is printed.

The letters slice contains three letters and the someLetters slice is declared to have a length of two.

The copy() function copies elements from one slice to another slice, but doesn't copy all the elements over if there isn't room.

In this example, someLetters only has room for the first two elements in letters.