D. Index out of range error when assigning to slice[2]
Solution
Step 1: Check slice length
slice := arr[1:3] includes elements at indices 1 and 2, length 2.
Step 2: Accessing slice[2]
slice[2] tries to access third element (index 2), which is out of range.
Final Answer:
Index out of range error when assigning to slice[2] -> Option D
Quick Check:
Slice length 2, index 2 invalid = C [OK]
Hint: Slice length limits valid indices from 0 to len-1 [OK]
Common Mistakes:
Assuming slice length equals array length
Using invalid slice indices
Ignoring runtime panics
5. Given the array arr := [5]int{1, 2, 3, 4, 5}, you create two slices: slice1 := arr[1:4] slice2 := arr[2:5] If you set slice1[1] = 99, what will be the content of slice2?
hard
A. [99 4 5]
B. [3 99 5]
C. [3 4 5]
D. [2 99 5]
Solution
Step 1: Identify slice1 and slice2 elements
slice1 = arr[1:4] = elements at indices 1,2,3 -> [2,3,4] slice2 = arr[2:5] = elements at indices 2,3,4 -> [3,4,5]
Step 2: Modify slice1[1]
slice1[1] is element at arr index 2 (value 3), changed to 99. So arr becomes [1,2,99,4,5].