Challenge - 5 Problems
Slice Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of slice capacity and length
What is the output of this Go program that uses slices?
Go
package main import "fmt" func main() { arr := [5]int{10, 20, 30, 40, 50} s := arr[1:4] fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Remember that length is the number of elements in the slice, capacity is from the start of the slice to the end of the underlying array.
✗ Incorrect
The slice s includes elements at indices 1, 2, 3 of arr, so length is 3. Capacity is from index 1 to the end of arr, which is 4 elements.
🧠 Conceptual
intermediate2:00remaining
Why slices are preferred over arrays in Go
Which reason best explains why slices are used instead of arrays in Go?
Attempts:
2 left
💡 Hint
Think about flexibility in size when working with collections.
✗ Incorrect
Slices are wrappers around arrays that allow dynamic resizing and flexible use, while arrays have fixed size determined at compile time.
🔧 Debug
advanced2:00remaining
Identify the runtime error with slices
What error will this Go code produce when run?
Go
package main import "fmt" func main() { s := []int{1, 2, 3} fmt.Println(s[3]) }
Attempts:
2 left
💡 Hint
Check the valid indices for a slice of length 3.
✗ Incorrect
The slice s has indices 0,1,2. Accessing s[3] causes a runtime panic due to index out of range.
❓ Predict Output
advanced2:00remaining
Effect of appending on slice capacity
What is the output of this Go program?
Go
package main import "fmt" func main() { s := make([]int, 2, 4) s[0], s[1] = 10, 20 s = append(s, 30, 40, 50) fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Appending beyond capacity doubles the capacity.
✗ Incorrect
Initial slice has length 2 and capacity 4. Appending 3 elements exceeds capacity, so Go allocates a new underlying array with doubled capacity (8). Length becomes 5.
🧠 Conceptual
expert3:00remaining
Why slices improve memory efficiency in Go
Which statement best explains how slices improve memory efficiency compared to arrays?
Attempts:
2 left
💡 Hint
Think about how slices reference data and how that affects copying.
✗ Incorrect
Slices are descriptors pointing to an underlying array. Passing slices to functions passes the descriptor, not the whole data, saving memory and time.