Challenge - 5 Problems
Slice Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Understanding slice length and capacity after slicing
What is the output of this Go program?
Go
package main import "fmt" func main() { s := []int{10, 20, 30, 40, 50} t := s[1:3] fmt.Println(len(t), cap(t)) }
Attempts:
2 left
💡 Hint
Remember: 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 t = s[1:3] has length 3-1=2. Its capacity is from index 1 to the end of s, which is 5-1=4.
❓ Predict Output
intermediate2:00remaining
Effect of append on slice capacity
What will be printed by this Go program?
Go
package main import "fmt" func main() { s := make([]int, 2, 4) s[0], s[1] = 1, 2 s = append(s, 3) fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Appending increases length by 1; capacity stays the same if there is room.
✗ Incorrect
Initial slice has length 2 and capacity 4. Append adds one element, length becomes 3, capacity remains 4.
❓ Predict Output
advanced2:00remaining
Slice capacity after reslicing
What is the output of this Go code?
Go
package main import "fmt" func main() { s := []int{1, 2, 3, 4, 5} t := s[1:4] u := t[1:3] fmt.Println(len(u), cap(u)) }
Attempts:
2 left
💡 Hint
Capacity of a slice is from its start index to the end of the underlying array.
✗ Incorrect
t = s[1:4] has length 3 and capacity 4 (from index 1 to 5). u = t[1:3] starts at s index 2, length 2, capacity 3 (from index 2 to 5).
❓ Predict Output
advanced2:00remaining
Appending beyond capacity creates new array
What will this Go program print?
Go
package main import "fmt" func main() { s := []int{1, 2, 3} t := s[:2] t = append(t, 4, 5) fmt.Println(len(t), cap(t)) }
Attempts:
2 left
💡 Hint
Appending more elements than capacity causes a new underlying array with larger capacity.
✗ Incorrect
t starts with length 2 and capacity 3. Appending two elements increases length to 4, exceeding capacity, so Go allocates a new array with larger capacity, usually doubling to 6.
❓ Predict Output
expert2:00remaining
Slice capacity and length with nil slice and append
What is the output of this Go 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. Append allocates new underlying array.
✗ Incorrect
Initially s is nil, so length and capacity are 0. After append, length is 1 and capacity is at least 1.