-2
package main

import "fmt"

func main() {
    is := []int{1, 2}

    fmt.Println(is[2:]) // no panic here - this includes is[2] which is out of bound still no panic
    fmt.Println(is[3:]) // but panic here
    fmt.Println(is[2]) // panic here which is acceptable
}

In above mentioned program, there is no panic for is[2:] even though we are accessing element from is[2] to on wards and the slice is having only 2 elements. Why is it so?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ganeshdip
  • 389
  • 2
  • 10
  • 4
    *"Why is it so?"* Slicing is not indexing. `is[2:]` is not "accessing" `is[2]`. – mkopriva May 09 '20 at 09:49
  • 1
    @mkopriva Yeah, but then slicing from index 2 should not be allowed as it is not present. let me rephrase it ```is[2:]``` means elements from ```is[2]``` till the end of ```is[]```. – Ganeshdip May 09 '20 at 09:51

1 Answers1

2

The go spec on slice expressions spells out the requirements for indices used in slicing:

The indices are in range if 0 <= low <= high <= max <= cap(a), otherwise they are out of range.

As for index expressions, the relevant requirement is:

the index x is in range if 0 <= x < len(a), otherwise it is out of range

Your slice has len(a) == cap(a) == 2. Your three test cases are:

  • slicing: low == 2 which is equal to cap(a): in range
  • slicing: low == 3 which is greater than cap(a): out of range
  • indexing: x == 2 which is equal to len(a): out of range
Marc
  • 19,394
  • 6
  • 47
  • 51