GOLANG

The anatomy of Slices in Go

Slices are like Arrays but they can vary in length.

Uday Hiwarale
RunGo
Published in
13 min readSep 10, 2018

--

(source: pexels.com)

What is a slice

A slice is just like an array which is a container to hold elements of the same data type but slice can vary in size.

slice is a composite data type and because it is composed of primitive data type (see variables lesson for primitive data types).

Syntax to define a slice is pretty similar to that of an array but without specifying the elements count. Hence s is a slice.

var s []int

Above code will create a slice of data type int that means it will hold elements of data type int. But what is a zero-value of a slice? As we saw in arrays, zero value of an array is an array with all its elements being zero-value of data type it contains.

Like an array of int with size n will have n zeroes as its elements because of zero value of int is 0. But in the case of slice, zero value of slice defined with the syntax above is nil. Below program will return true.

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

--

--