Challenge - 5 Problems
Go Slice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of slice length and capacity
What is the output of this Go program?
Go
package main import "fmt" func main() { s := make([]int, 3, 5) fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Remember: len is the number of elements, cap is the total allocated space.
✗ Incorrect
The slice is created with length 3 and capacity 5, so len(s) is 3 and cap(s) is 5.
❓ Predict Output
intermediate2:00remaining
Slice literal with capacity
What will this program print?
Go
package main import "fmt" func main() { s := []int{1, 2, 3, 4} fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Slice literals have capacity equal to their length.
✗ Incorrect
A slice literal creates a slice with length and capacity equal to the number of elements.
❓ Predict Output
advanced2:00remaining
Appending beyond capacity
What is the output of this Go program?
Go
package main import "fmt" func main() { s := make([]int, 2, 3) s[0], s[1] = 10, 20 s = append(s, 30) s = append(s, 40) fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Appending beyond capacity causes the slice to grow, usually doubling capacity.
✗ Incorrect
The initial capacity is 3. After appending the 4th element, capacity grows, typically doubling to 6.
❓ Predict Output
advanced2:00remaining
Slice zero value behavior
What happens when you run this program?
Go
package main import "fmt" func main() { var s []int fmt.Println(len(s), cap(s)) s = append(s, 1) fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
A nil slice has zero length and capacity but can be appended to.
✗ Incorrect
Initially, s is nil with length and capacity 0. After append, length and capacity become 1.
❓ Predict Output
expert2:00remaining
Slice header and underlying array
What will this program print?
Go
package main import "fmt" func main() { arr := [4]int{1, 2, 3, 4} s := arr[1:3] s = append(s, 5) fmt.Println(arr) fmt.Println(s) }
Attempts:
2 left
💡 Hint
Appending within capacity modifies the shared underlying array.
✗ Incorrect
s := arr[1:3] has length 2, capacity 3 (arr[1:4]). Appending 5 increases length to 3 within capacity, so it overwrites arr[3] with 5. Now arr is [1 2 3 5] and s is [2 3 5].