0
0
Goprogramming~20 mins

Slice creation in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Slice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))
}
A5 3
B3 5
C0 5
D3 3
Attempts:
2 left
💡 Hint
Remember: len is the number of elements, cap is the total allocated space.
Predict Output
intermediate
2: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))
}
A3 4
B4 8
C4 4
D4 0
Attempts:
2 left
💡 Hint
Slice literals have capacity equal to their length.
Predict Output
advanced
2: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))
}
A4 6
B4 3
C4 4
D3 3
Attempts:
2 left
💡 Hint
Appending beyond capacity causes the slice to grow, usually doubling capacity.
Predict Output
advanced
2: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))
}
A
0 1
1 1
B
0 0
1 0
C
1 1
1 1
D
0 0
1 1
Attempts:
2 left
💡 Hint
A nil slice has zero length and capacity but can be appended to.
Predict Output
expert
2: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)
}
A
[1 2 3 5]
[2 3 5]
B
[1 2 3 4]
[2 3 5]
C
[1 2 3 4]
[2 3 4 5]
D
[1 2 3 4]
[2 3 4]
Attempts:
2 left
💡 Hint
Appending within capacity modifies the shared underlying array.