Arrays and Slices

Go arrays and slices are essentially C arrays and pointers, with an excellent set of improvements.

As in C, Go arrays are created with a non-negative, constant size, and are indexed from zero to size less 1. Unlike C, the array remembers its size, and you can find it using the built-in len function. And, if you subscript the array out of bounds, Go will complain. Downright civilized.

Slices serve the same purpose as pointers into an array in C. A pointer specifies a position in an array, and you can subscript it to find a position later in the array. But the pointer doesn't know where the end of the array is, so the system can't (and doesn't) bounds-check your subscript, and you can't ask for any kind of size to do it yourself. Go slices, on the other hand, represent a portion of an array by recording both starting and ending positions. It can denote the whole array, or any part. You can subscript the slice to find a position within it, and the system will bounds-check your subscript. You can change the starting or ending points of the slice, so long as they remain in the array, and the system checks your changes when you do.

So Go's array and slice types are essentially C's array and pointer types (when the pointer points into an array), but with bounds checking all around.

var arr [8]int var sl []int sl = arr[2:7]


The array arr has positions 0 to 7. The slice sl refers to positions 2 through 6, which it denotes with subscripts 0 through 4. So now arr[3] is the same thing as sl[1].