2.5 KiB
Capacity and Append Mechanics Quiz
What is the difference between the length and capacity of a slice?
- They are the same
- The length is always greater than the capacity
- The capacity is always greater than the capacity
- The length describes the length of a slice but a capacity describes the length of the backing array beginning from the first element of the slice CORRECT
2: The length is never greater than the capacity.
3: The length and capacity of a slice can be equal.
What is the capacity of a nil slice?
- It is equal to its length + 1
- It is nil
- 0 CORRECT
- 1
2: The capacity's type is int, it cannot be nil.
What are the length and capacity of the slice value?
[]string{"I", "have", "a", "great", "capacity"}
- Length: 5 - Capacity: 5 CORRECT
- Length: 0 - Capacity: 5
- Length: 5 - Capacity: 10
- Length: 10 - Capacity: 10
1: That's right! A slice literal creates a new slice value with equal length and capacity.
What are the length and capacity of the 'words' slice?
words := []string{"lucy", "in", "the", "sky", "with", "diamonds"}
words = words[:0]
- Length: 0 - Capacity: 0
- Length: 6 - Capacity: 6
- Length: 0 - Capacity: 6 CORRECT
- Length: 5 - Capacity: 10
3: Right!
words[:0]
slices for 0 elements, which in turn returns a slice with zero-length. Because thewords
slice points to the same backing array, its capacity is equal to 6.
What are the length and capacity of the 'words' slice?
words := []string{"lucy", "in", "the", "sky", "with", "diamonds"}
words = words[0:]
- Length: 0 - Capacity: 0
- Length: 6 - Capacity: 6 CORRECT
- Length: 0 - Capacity: 6
- Length: 5 - Capacity: 10
2: Right!
words[0:]
slices for the rest of the elements, which in turn returns a slice with the same length as the original slice: 6. Beginning from the first array element, thewords
slice's backing array contains 6 elements; so its capacity is also 6.
What are the length and capacity of the 'words' slice?
words := []string{"lucy", "in", "the", "sky", "with", "diamonds"}
words = words[2:cap(words)-2]
- Length: 4 - Capacity: 6
- Length: 6 - Capacity: 4
- Length: 2 - Capacity: 6
- Length: 2 - Capacity: 4 CORRECT
4: Right!
words[2:cap(words)-2]
is equal towords = words[2:4]
, so it returns:["the" "sky"]
. So, its length is 2. But there are 4 more elements (["the" "sky" "with" "diamonds"]
) in the backing array, so the capacity is 4.