Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice declarations like [0:2]

Tags:

slice

go

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]  
like image 394
ABSimon Avatar asked Jan 26 '23 16:01

ABSimon


2 Answers

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.

like image 200
Eli Bendersky Avatar answered Jan 29 '23 06:01

Eli Bendersky


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

like image 28
atakanyenel Avatar answered Jan 29 '23 06:01

atakanyenel