5. Given a queue implemented as a slice queue := []int{5, 10, 15}, write the correct Go code snippet to safely peek the front element and handle the empty queue case by printing "Empty" if no elements exist.
hard
A. if len(queue) > 0 {
fmt.Println(queue[0])
} else {
fmt.Println("Empty")
}
B. fmt.Println(queue[0])
C. if queue != nil {
fmt.Println(queue[0])
} else {
fmt.Println("Empty")
}
D. if len(queue) == 0 {
fmt.Println(queue[0])
} else {
fmt.Println("Empty")
}
Solution
Step 1: Check queue length before access
Use len(queue) > 0 to ensure queue has elements.
Step 2: Print front or "Empty"
If queue has elements, print queue[0]; else print "Empty".
Final Answer:
if len(queue) > 0 {
fmt.Println(queue[0])
} else {
fmt.Println("Empty")
} -> Option A
Quick Check:
Check length before access to avoid panic [OK]
Hint: Always check length before peeking front [OK]
Common Mistakes:
Not checking length before access
Checking nil instead of length
Reversing if-else logic
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.