Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading