Challenge - 5 Problems
Slice Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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) }
Attempts:
2 left
💡 Hint
Remember that append adds elements to the end of the slice and returns the new slice.
✗ Incorrect
The append function adds the elements 4 and 5 to the slice s, resulting in [1 2 3 4 5].
❓ Predict Output
intermediate2: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) }
Attempts:
2 left
💡 Hint
Use the ... operator to append all elements of one slice to another.
✗ Incorrect
The append function with b... appends all elements of b to a, resulting in [1 2 3 4].
❓ Predict Output
advanced2: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) }
Attempts:
2 left
💡 Hint
Appending to a nil slice creates a new slice with the appended elements.
✗ Incorrect
Appending to a nil slice works fine and results in a slice with the new element.
❓ Predict Output
advanced2: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) } }
Attempts:
2 left
💡 Hint
Slice capacity doubles when exceeded during append.
✗ Incorrect
The slice starts with capacity 2. When the third element is appended, capacity grows to 4.
🧠 Conceptual
expert3: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)
}
Attempts:
2 left
💡 Hint
Appending to s2 modifies the underlying array shared with s1 if capacity allows.
✗ Incorrect
s2 is a slice of s1 with length 2 but capacity 3. Appending 4 modifies the shared array, changing s1's third element.