L
L
Luke LikeSkywalker2018-12-04 06:16:49
go
Luke LikeSkywalker, 2018-12-04 06:16:49

Index out of range why is this happening?

I'm trying to solve a problem. Tried through range via len(), hardcoded i<3 still getting "index out of range" error

package main

import (
  "fmt"
)

func main() {
  a:=[]int32{2,56,4}
  b:=[]int32{7,56,6}
  fmt.Println(compareTriplets(a,b))
}

func compareTriplets(a []int32, b []int32) []int32 {
    scores:=[]int32{}
    for i:= 0; i < 3; i++ {
        if a[i] > b[i]{
            scores[0]++
        }
        if a[i] < b[i]{
            scores[1]++
        }
    }
      return scores
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abbaboka, 2018-12-04
@oolooq

This is not possible: score - no size. Zero size. You cannot assign either to the first element, as written above (numbering from zero, so index 0 means the first element) or to subsequent ones. These elements simply do not exist. It is necessary or explicitly specify the size before use, as Vasily Melnikov wrote , there are 2 methods. or dynamically resize via . Specifically for your code - it is expedient through
scores = append(scores, newItem)var scores [размер]тип

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question