[Solved] Panic Runtime Error index out of range [3] with length 3


Let’s say that you pass the string XII to your function. That makes len(s) 3, which means that the body of your loop would (if the panic didn’t occur) execute 4 times (when i is 0, 1, 2 and 3 since your condition is i <= len(s).

On the iteration where i is 2 (i.e. it refers to the second I in XII, the last character), when the line

nextInt := romanNum[s[i+1]]

attempts to access the next character (i+1 will be 3) then it will be out of bounds. Remember, slices/arrays are 0 indexed. This is the reason for the panic.

It’s also worth nothing that if the panic did not occur when i was 2, then it would certainly occur during the next iteration where i is 3, since 3 is out of bounds for s, on the following line:

currentInt := romanNum[s[i]]

To fix the issue, you need to reconsider how you approach the condition of the loop. Using <= here is likely to cause you a problem. Also, within the body of the loop, you need to consider that when you’re looking at the last character in the string, there is not a next character, but your code just assumes that there is. Addressing both of these problems should help you overcome the issue.

solved Panic Runtime Error index out of range [3] with length 3