Full slice expressions

November 29, 2023

Full slice expressions

The primary expression

a[low : high : max]

constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice’s capacity by setting it to max - low.

So I’ll be honest here and say I’ve never used this slice expression format. I’ve been vaguely aware that it exists, but I’ve never felt the need for it. But I’ll be keeping my eye out for opportunities to use it from now on.

But we’ll breeze through this one today. Although it’s a lot of text, there aren’t any surprises here at all, so it’s easy comprehension.

Only the first index may be omitted; it defaults to 0.

Ah shucks, so we won’t be seeing any ASCII art in the form of s[::] or s[:8:]. Ah well. I guess there’s always Lisp…

The core type of a must be an array, pointer to array, or slice (but not a string). After slicing the array a

a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]

the slice t has type []int, length 2, capacity 4, and elements

t[0] == 2
t[1] == 3

As for simple slice expressions, if a is a pointer to an array, a[low : high : max] is shorthand for (*a)[low : high : max]. If the sliced operand is an array, it must be addressable.

The indices are in range if 0 <= low <= high <= max <= cap(a), otherwise they are out of range. A constant index must be non-negative and representable by a value of type int; for arrays, constant indices must also be in range. If multiple indices are constant, the constants that are present must be in range relative to each other. If the indices are out of range at run time, a run-time panic occurs.

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .