0
0
Goprogramming~20 mins

Why slices are used in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Slice Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))
}
A4 3
B3 4
C4 4
D3 3
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.
🧠 Conceptual
intermediate
2:00remaining
Why slices are preferred over arrays in Go
Which reason best explains why slices are used instead of arrays in Go?
ASlices provide dynamic size and can grow or shrink, arrays have fixed size.
BSlices cannot be passed to functions, arrays can.
CSlices are stored on the stack, arrays are stored on the heap.
DSlices do not reference underlying data, arrays do.
Attempts:
2 left
💡 Hint
Think about flexibility in size when working with collections.
🔧 Debug
advanced
2: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])
}
APrints 0
BCompilation error: index out of range
CIndex out of range runtime panic
DNo error, prints 3
Attempts:
2 left
💡 Hint
Check the valid indices for a slice of length 3.
Predict Output
advanced
2: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))
}
A5 10
B5 4
C5 5
D5 8
Attempts:
2 left
💡 Hint
Appending beyond capacity doubles the capacity.
🧠 Conceptual
expert
3:00remaining
Why slices improve memory efficiency in Go
Which statement best explains how slices improve memory efficiency compared to arrays?
ASlices share the underlying array, avoiding copying data when passed to functions.
BSlices always allocate new memory on append, preventing memory leaks.
CSlices store data inline, reducing pointer overhead compared to arrays.
DSlices automatically compress data to save memory.
Attempts:
2 left
💡 Hint
Think about how slices reference data and how that affects copying.