index out of range [113] with length 10

I am currently trying to make a function to decrypt messages from qwerty… -> abcdef…. Currently I have

func Decrypt(strToDecrypt string) string {
 encrStrng := []rune(strings.ToLower(strToDecrypt))
 var decrStrng string = ""

 for _, i := range encrStrng {
   switch encrStrng[i] {
   case 'q'
    decrStrng += "a"
// not gonna type the rest but its q>a, w>b, etc etc.
 }
}

Whenever i try fmt.Println(Decrypt("qwerty")) (in main function ofc) just as a test, it returns
panic: runtime error: index out of range [113] with length 10. Error is at the switch statement, in particular. I could not find anything on this (specific) issue.

>Solution :

In a range over an array, the first value is the index, the second is the element value. You’re using the element value as an index, in order to get the element value. You should either use the index:

 for i := range encrStrng {
   switch encrStrng[i] {

Or use the value:

 for _, i := range encrStrng {
   switch i {

range is covered in the Tour of Go.

Leave a Reply