0
0
Goprogramming~20 mins

Appending to slices in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Slice Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Appending elements to a slice
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    s := []int{1, 2, 3}
    s = append(s, 4, 5)
    fmt.Println(s)
}
A[1 2 3 4 5]
B[1 2 3]
C[4 5]
DCompilation error
Attempts:
2 left
💡 Hint
Remember that append adds elements to the end of the slice and returns the new slice.
Predict Output
intermediate
2:00remaining
Appending one slice to another
What will be printed by this Go program?
Go
package main
import "fmt"
func main() {
    a := []int{1, 2}
    b := []int{3, 4}
    a = append(a, b...)
    fmt.Println(a)
}
ARuntime panic
B[1 2 [3 4]]
C[3 4 1 2]
D[1 2 3 4]
Attempts:
2 left
💡 Hint
Use the ... operator to append all elements of one slice to another.
Predict Output
advanced
2:00remaining
Appending to nil slice
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    var s []int
    s = append(s, 10)
    fmt.Println(s)
}
A[10]
Bnil
C[]
DCompilation error
Attempts:
2 left
💡 Hint
Appending to a nil slice creates a new slice with the appended elements.
Predict Output
advanced
2:00remaining
Appending inside a loop and slice capacity
What will be the output of this Go program?
Go
package main
import "fmt"
func main() {
    s := make([]int, 0, 2)
    for i := 1; i <= 3; i++ {
        s = append(s, i)
        fmt.Printf("len=%d cap=%d slice=%v\n", len(s), cap(s), s)
    }
}
A
len=1 cap=2 slice=[1]
len=2 cap=2 slice=[1 2]
len=3 cap=2 slice=[1 2 3]
B
len=1 cap=2 slice=[1]
len=2 cap=2 slice=[1 2]
len=3 cap=4 slice=[1 2 3]
C
len=1 cap=1 slice=[1]
len=2 cap=2 slice=[1 2]
len=3 cap=3 slice=[1 2 3]
D
len=1 cap=2 slice=[1]
len=2 cap=4 slice=[1 2]
len=3 cap=8 slice=[1 2 3]
Attempts:
2 left
💡 Hint
Slice capacity doubles when exceeded during append.
🧠 Conceptual
expert
3:00remaining
Understanding slice append and underlying array sharing
Consider this Go code snippet. What will be the output? package main import "fmt" func main() { s1 := []int{1, 2, 3} s2 := s1[:2] s2 = append(s2, 4) fmt.Println("s1:", s1) fmt.Println("s2:", s2) }
ARuntime panic: index out of range
B
s1: [1 2 3]
s2: [1 2 4]
C
s1: [1 2 4]
s2: [1 2 4]
D
s1: [1 2 3]
s2: [1 2 3 4]
Attempts:
2 left
💡 Hint
Appending to s2 modifies the underlying array shared with s1 if capacity allows.