0
0
Goprogramming~20 mins

Slice and array relationship in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Slice and Array Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of modifying a slice element
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    arr := [3]int{1, 2, 3}
    s := arr[:]
    s[1] = 10
    fmt.Println(arr)
}
A[1 2 3]
B[1 10 3]
C[10 2 3]
D[1 10 10]
Attempts:
2 left
💡 Hint
Slices share the underlying array with the original array.
Predict Output
intermediate
2:00remaining
Length and capacity of a slice
What will be printed by this Go code?
Go
package main
import "fmt"
func main() {
    arr := [5]int{1, 2, 3, 4, 5}
    s := arr[1:4]
    fmt.Println(len(s), cap(s))
}
A3 4
B3 3
C4 4
D4 3
Attempts:
2 left
💡 Hint
Length is the number of elements in the slice; capacity is from the start of the slice to the end of the array.
🔧 Debug
advanced
2:00remaining
Why does this slice append not change the original array?
Consider this Go code snippet. What is the output and why?
Go
package main
import "fmt"
func main() {
    arr := [3]int{1, 2, 3}
    s := arr[:2]
    s = append(s, 4)
    fmt.Println(arr)
    fmt.Println(s)
}
A[1 2 3]\n[1 2 4]
B[1 2 4]\n[1 2 4]
C[1 2 3]\n[1 2 3 4]
D[1 2 3]\n[1 2 3]
Attempts:
2 left
💡 Hint
Appending to a slice may create a new underlying array if capacity is exceeded.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in slice declaration
Which option contains a syntax error in slice or array usage?
As := arr[1:4]
Barr := [3]int{1, 2, 3}
Cs := arr[1..3]
Ds := []int{1, 2, 3}
Attempts:
2 left
💡 Hint
Go slice syntax uses a single colon, not two dots.
🧠 Conceptual
expert
2:00remaining
Effect of modifying a slice after re-slicing
Given the code below, what is the output?
Go
package main
import "fmt"
func main() {
    arr := [5]int{10, 20, 30, 40, 50}
    s1 := arr[1:4]
    s2 := s1[1:3]
    s2[0] = 100
    fmt.Println(arr)
}
A[10 20 30 100 50]
B[10 100 30 40 50]
C[10 20 30 40 50]
D[10 20 100 40 50]
Attempts:
2 left
💡 Hint
Slices share the same underlying array. Indexes are relative to the original array.