Search code examples
stringgoindexingpanic

panic: index out of range in Go when trying to access string element


I am currently learning how to code in Go and I am stuck with a problem that happen at line 43 and 44 of my code, i am trying to convert one element of "num" and "den" into a number so i can later use it do the calculation i want but i get the following message :

panic: runtime error: index out of range

goroutine 1 [running]:
main.iterate_transfer(0x7ffecd96f050, 0x3, 0x7ffecd96f054, 0x3)
        /home/mlg/Programming/project/107transfer_2019/107transfer.go:43 +0x3af
main.main()
        /home/mlg/Programming/project/107transfer_2019/107transfer.go:28 +0xac

I tried to printf the len and content of the "den" string and it contain the value I want at the right position, so I don't unterstand why i can't acces a single element of it

I passed "7*2*6" to num_str and "2*4*3" to den_str

My code :

 34 func iterate_transfer(num_str, den_str string) () {
 35     result := 0.0
 36 
 37     for x := 0.0; x <= 1.00; x += 0.001 {
 38         num := strings.Split(num_str, "*")
 39         den := strings.Split(den_str, "*")
 40         power_num := len(num)
 41         power_den := len(den)
 42         for s := len(num); s > 0; s-- {
 43             num_nb, _ := strconv.Atoi(num[s])
 44             den_nb, _ := strconv.Atoi(den[s])
 45             result += math.Pow(float64(num_nb), float64(power_den)) /     math.Pow(float64(den_nb), float64(power_den))
 46             power_num--
 47             power_den--       
 48         }   
 49         fmt.Println(x, " -> ", result, "\n")
 50     }   
 51 }   

Thanks you in advance for helping me !


Solution

  • The len builtin method, return the size of the given element. Due to the fact that the index start from 0, you need to:

    1. Check if the len is greater than 0;
    2. Subtract -1 in order to access the index