0
0
Goprogramming~5 mins

Slice creation in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a slice in Go?
A slice is a flexible and dynamic view into the elements of an array. It allows you to work with sequences of elements without fixed size.
Click to reveal answer
beginner
How do you create a slice with predefined elements in Go?
You can create a slice by listing elements inside square brackets without specifying size, like: slice := []int{1, 2, 3}.
Click to reveal answer
intermediate
What does the built-in function make do when creating a slice?
make creates a slice with a specified length and capacity, for example: make([]int, 3, 5) creates a slice of length 3 and capacity 5.
Click to reveal answer
intermediate
What is the difference between length and capacity of a slice?
Length is the number of elements the slice currently holds. Capacity is the total number of elements the slice can hold before needing to grow.
Click to reveal answer
beginner
How do you create an empty slice in Go?
You can create an empty slice by declaring it without elements: var s []int or with make([]int, 0).
Click to reveal answer
Which of the following creates a slice with 5 integers initialized to zero?
Amake([]int, 5)
B[]int{5}
Cmake([]int, 0, 5)
Dvar s [5]int
What is the length of the slice created by make([]string, 3, 10)?
A3
B10
C0
D13
How do you declare a slice with elements 10, 20, and 30?
Aslice := [3]int{10, 20, 30}
Bslice := []int{10, 20, 30}
Cslice := make([]int, 3)
Dslice := []int(10, 20, 30)
What happens if you append an element to a slice that has reached its capacity?
AThe element is ignored.
BThe program crashes.
CThe slice automatically grows to accommodate the new element.
DYou must manually increase the capacity before appending.
Which of these is NOT a valid way to create an empty slice?
Avar s []int
Bs := []int{}
Cs := make([]int, 0)
Ds := make([]int, 5)
Explain how to create a slice in Go with a specific length and capacity using the make function.
Think about the parameters make takes for slices.
You got /4 concepts.
    Describe the difference between a slice's length and capacity and why it matters.
    Consider what happens when you add elements beyond the current capacity.
    You got /3 concepts.