0
0
Goprogramming~5 mins

Slicing 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 lets you work with parts of an array without copying data.
Click to reveal answer
beginner
How do you create a slice from an array or another slice?
You use the slicing syntax: slice := array[start:end]. This creates a new slice from index start up to but not including end.
Click to reveal answer
beginner
What happens if you omit the start or end index in a slice operation?
If you omit start, it defaults to 0 (start of the array). If you omit end, it defaults to the length of the array or slice.
Click to reveal answer
intermediate
What is the difference between length and capacity of a slice?
Length is how many elements the slice currently holds. Capacity is how many elements the slice can hold before it needs to grow (based on the underlying array).
Click to reveal answer
intermediate
How can slicing affect the original array?
Slices share the same underlying array. Changing an element in a slice changes the same element in the original array and other slices sharing it.
Click to reveal answer
What does arr[2:5] return if arr is a slice?
AElements from index 3 to 5
BElements from index 2 up to and including 5
CElements from index 0 to 5
DElements from index 2 up to but not including 5
What is the length of the slice created by slice := arr[:]?
ALength of arr
B0
CCapacity of arr
DUndefined
If you change an element in a slice, what happens to the original array?
AThe original array changes at that element
BThe original array stays the same
CA new array is created
DThe slice becomes invalid
What does the capacity of a slice represent?
ANumber of slices created from the array
BCurrent number of elements in the slice
CMaximum number of elements the slice can hold before resizing
DSize of the underlying array
Which of these is a valid way to create a slice from an array arr?
Aslice := arr(1,4)
Bslice := arr[1:4]
Cslice := arr[1..4]
Dslice := arr.slice(1,4)
Explain how slicing works in Go and how it relates to the underlying array.
Think about how slices are views into arrays, not copies.
You got /4 concepts.
    Describe the difference between the length and capacity of a slice and why it matters.
    Consider what happens when you append elements to a slice.
    You got /4 concepts.