4

I don't understand slice declarations in Go.

For, me a declaration for the first and second element of an array must be 0:1. But it is 0:2. Why? How should I read this, from zero to 2 minus 1 (all the time)?

var slice = array[0:2]  
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ABSimon
  • 651
  • 1
  • 6
  • 18

2 Answers2

7

Slice bounds are half open, this is very standard for many programming languages. One advantage is that it makes the length of the range apparent (2-0=2). Specifically, it's common to do this:

s[start:start+len]

And it's obvious that this selects len elements from the slice, starting with start. If the range would be fully closed (both bounds included), there would have to be a lot of -1s in code to deal with slicing and subslicing.

It works similarly in C++ ranges and Python, etc. Here's some reasoning from a C++ answer, attributed to Dijkstra:

  • You want the size of the range to be a simple difference end − begin;

  • including the lower bound is more "natural" when sequences degenerate to empty ones, and also because the alternative (excluding the lower bound) would require the existence of a "one-before-the-beginning" sentinel value.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
1

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

a[low : high]

This selects a half-open range which includes the first element, but excludes the last one.

This is from Golang's page on slices https://tour.golang.org/moretypes/7

atakanyenel
  • 1,367
  • 1
  • 15
  • 20