Fix

"invalid string index" in Go

Fix 'invalid string index' in Go by checking string bounds or converting to a rune slice before indexing.

The "invalid string index" panic occurs because you are accessing a string index that is out of bounds or using an integer index on a string without converting it to a rune slice first. In Go, strings are UTF-8 encoded, so indexing a string directly by byte position can lead to unexpected behavior if the string contains multi-byte characters. To fix this, ensure your index is within the valid range of the string's byte length, or convert the string to a rune slice if you need to access characters by their Unicode code point.

// Incorrect: Direct indexing on a string with multi-byte characters
s := "hello"
if len(s) > 0 {
    // This works for ASCII but fails for multi-byte runes if index is out of bounds
    char := s[0] // Returns a byte, not a rune
}

// Correct: Check bounds and use rune conversion for multi-byte characters
s := "hello"
if len(s) > 0 {
    runes := []rune(s)
    if len(runes) > 0 {
        char := runes[0] // Returns the first rune
    }
}