0
0
Goprogramming~5 mins

Common slice operations in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AA new underlying array is allocated with more capacity, and the slice points to it.
BThe element is discarded because the slice is full.
CThe program crashes with an error.
DThe element replaces the last element in the slice.
How do you get a slice of the first 3 elements of a slice named data?
Adata[0:3]
Bdata[3:0]
CBoth A and D
Ddata[:3]
Which function is used to copy elements from one slice to another?
Aappend
Bcopy
Cslice
Dmove
How do you remove the element at index 2 from a slice named items?
Aitems = append(items[3:], items[:2]...)
Bitems = items[2:]
Citems = items[:2]
Ditems = append(items[:2], items[3:]...)
What is the length of a newly created slice with make([]int, 5, 10)?
A5
B10
C0
D15
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.