Why a slice variable(not initialized) not nil when printed?


(Warlord X) #1

go newbie here. trying to understand some basics.
Since slice is a reference to an underlying array, can it be a pointer ?

When I create a new variable for slice and try to print it’s address, should it not be nil ? Then why do I get it as ‘[]’

	var sliceTemp []int
	fmt.Println(sliceTemp)

https://play.golang.org/p/vsVyPng_cJq


(Jakob Borg) #2

It’s more than a reference to an array, you can think of it as a small struct. Nonetheless the default value is nil (nil array pointer, zero length and capacity) and if you print the comparison to nil you will get true. Println “pretty prints” it as the empty slice [] because it is for all intents and purposes equivalent to a non-nil but empty slice and this is more informative than a plain ”nil”.

Oh, and I think this is the canonical article on how slices work: https://blog.golang.org/go-slices-usage-and-internals


(Yamil Bracho) #3

You can check if it is nil doing

fmt.Println(sliceTemp == nil)

(Warlord X) #4

Hello @calmh, thank you for your response and clarifying it. Sorry for asking this based on your response, why would it be equivalent to a non-nil? If I understand it, till this link it doesn’t allocate any memory for it, thereby when checked against == it give a nil. Which makes sense.


(Jakob Borg) #5

It’s equivalent in that it behaves the same and can be used in the same ways as an empty but non-nil slice.

I mean, when the length and capacity are both zero it doesn’t matter what the array pointer is because it will never be followed.


(Alessandro Giovanardi) #6
  • A slice has three components: a pointer (to values of underlying array), a length and a capacity.
  • Unlike arrays, slices length, capacity and values can be modified.
  • Slices are access windows to underlying arrays.

Let’s start with empty nil slice .
Zero value of a slice type is nil.
A nil slice has no underlying array. Iterations over a nil slice are legal but storing to nil slice will cause panic.

I have written a newbie guide/cheatsheet for Slices at link below if it can help: