0
0
Goprogramming~20 mins

Slice length and capacity in Go - Practice Problems & Coding Challenges

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
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))
}
A2 3
B3 4
C2 4
D3 5
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.
Predict Output
intermediate
2: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))
}
A3 3
B3 4
C4 4
D2 4
Attempts:
2 left
💡 Hint
Appending increases length by 1; capacity stays the same if there is room.
Predict Output
advanced
2: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))
}
A3 4
B2 4
C3 3
D2 3
Attempts:
2 left
💡 Hint
Capacity of a slice is from its start index to the end of the underlying array.
Predict Output
advanced
2: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))
}
A4 6
B4 4
C5 6
D5 4
Attempts:
2 left
💡 Hint
Appending more elements than capacity causes a new underlying array with larger capacity.
Predict Output
expert
2: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))
}
A
0 0
1 1
B
0 0
1 0
C
0 1
1 1
D
0 0
1 2
Attempts:
2 left
💡 Hint
A nil slice has zero length and capacity. Append allocates new underlying array.