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]
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 -1
s 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With