Slice expression result types

November 27, 2023

No live stream today. Next week I expect to be back at it!


Forgive me for not sending an email Friday. I spent the day in bed. 🛏️ But I’m back on my feet now!

So up to now we’ve learned how to use slice expressions… but what is the type that results? Well, you can probably guess. It’s pretty intuitive:

Simple slice expressions

Except for untyped strings, if the sliced operand is a string or slice, the result of the slice operation is a non-constant value of the same type as the operand. For untyped string operands the result is a non-constant value of type string. If the sliced operand is an array, it must be addressable and the result of the slice operation is a slice with the same element type as the array.

So the only exception to what might be considered “expectations” is that if you’re slicing an untyped string constant, the result is a typed non-constant string:

const str = "Untyped string constant"
sl := str[3:8] // sl is of type `string`

And honestly, this is even pretty expected, considering what we know about how untyped constants are assigned to variables. So nothing really to see here.

Then one last note to wrap up the section on simle slice expressions:

If the sliced operand of a valid slice expression is a nil slice, the result is a nil slice. Otherwise, if the result is a slice, it shares its underlying array with the operand.

var a [10]int
s1 := a[3:7]   // underlying array of s1 is array a; &s1[2] == &a[5]
s2 := s1[1:4]  // underlying array of s2 is underlying array of s1 which is array a; &s2[1] == &a[5]
s2[1] = 42     // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element

var s []int
s3 := s[:0]    // s3 == nil

So, if you slice a nil slice, you get back a nil slice. Unless you get a runtime panic, of course. The the only way to slice a nil slice is with both the low and high indexes either explicitly or implicitly 0. All four slice expressions below are functionally identical. Any other values would cause a runtime panic.

var s []int
s1 := s[:]
s2 := s[0:0]
s3 := s[0:]
s4 := s[:0]

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 .

Get daily content like this in your inbox!

Subscribe