A slice is a dynamically sized, flexible view over elements of an underlying array. Unlike an array, whose length is part of its type, a slice has no fixed size in its type. section 3.2.2
Work with slices through their three-part representation and built-in operations:
- Underlying array: a slice stores a pointer to its array. section 3.2.2
- Length: len reports the number of elements currently present. section 3.2.2
- Capacity: cap reports how many elements fit before reallocation is necessary. section 3.2.2
- Construction: make can specify length and capacity, while append adds elements and returns the resulting slice. section 3.2.2
- Iteration: range visits slice elements by index and value, or values alone when the index is unnecessary. section 3.5
Collecting books shared by bookworms
A book-digest CLI uses a slice to accumulate books found on multiple shelves: func findCommonBooks(bookworms []Bookworm) []Book { booksOnShelves := booksCount(bookworms) var commonBooks []Book for book, count := range booksOnShelves { if count > 1 { commonBooks = append(commonBooks, book) } } return commonBooks } A nil slice is a useful starting point: append grows it as matching books are discovered. Table-driven tests then check cases with no common book, one common book, and several bookworms sharing titles. section 3.2.2 section 2.6
Listing 3.16 bookworm.go: Implementing findCommonBooks()
// findCommonBooks returns books that are on more than one bookworm's shelf.
func findCommonBooks(bookworms []Bookworm) []Book {
booksOnShelves := booksCount(bookworms) #1
var commonBooks []Book
for book, count := range booksOnShelves { #2
if count > 1 { #3
commonBooks = append(commonBooks, book)
}
}
return commonBooks
}
Browse a complete findCommonBooks implementation that combines a slice parameter, map iteration, conditional filtering, and append. section 3.2.2















