Recall & Review
beginner
What is a slice in Go?
A slice in Go is a flexible, dynamically-sized view into the elements of an array. It provides access to a segment of an array and can grow or shrink as needed.
Click to reveal answer
beginner
How do you append an element to a slice?
Use the built-in
append function. For example: slice = append(slice, element) adds element to the end of slice.Click to reveal answer
intermediate
How can you remove an element at index i from a slice?
You can remove an element by slicing and combining parts:
slice = append(slice[:i], slice[i+1:]...). This skips the element at index i.Click to reveal answer
beginner
What does slicing a slice like
slice[a:b] do?It creates a new slice referencing elements from index
a up to but not including b. The original slice is not copied, just referenced.Click to reveal answer
intermediate
How do you copy elements from one slice to another?
Use the built-in
copy function: copy(dest, src) copies elements from src to dest. It copies up to the smaller length of the two slices.Click to reveal answer
What happens when you append an element to a slice that has no extra capacity?
✗ Incorrect
When appending to a slice with no extra capacity, Go allocates a new array with more space and copies existing elements before adding the new one.
How do you get a slice of the first 3 elements of a slice named
data?✗ Incorrect
Both
data[0:3] and data[:3] return a slice of the first 3 elements.Which function is used to copy elements from one slice to another?
✗ Incorrect
The built-in
copy function copies elements from a source slice to a destination slice.How do you remove the element at index 2 from a slice named
items?✗ Incorrect
Appending
items[:2] and items[3:] skips the element at index 2, effectively removing it.What is the length of a newly created slice with
make([]int, 5, 10)?✗ Incorrect
The length is 5, which is the number of initialized elements. The capacity is 10, the total space allocated.
Explain how to add and remove elements from a slice in Go.
Think about how you can combine parts of the slice to exclude an element.
You got /3 concepts.
Describe what happens internally when you append an element to a slice that is already full.
Consider how Go manages memory for slices when they grow.
You got /4 concepts.