Member-only story

Golang slice basics

Pierre-Marie Poitevin
4 min readMay 16, 2019

--

I noticed that, despite the many claims that slice is a very powerful go tool and can be used for so many data structure needs, some people, when confronted to a practical problem, don’t find them that natural and easy to use.

Most of the struggle I believe is due to the fact that slices are quite different than arrays in other languages, and also that a lot of the libraries that would be built for you in other languages are not native to go (I am thinking of queues for instance), then people are confronted with having to implement common data structures with slices, when they don’t necessarily need to go to such a low level in other languages such as Java.

Starting with arrays, there are a couple of different ways to initialize arrays in Go:

func initArray() {
var A [3]int
A[0] = 1
A[1] = 2
A[2] = 3
fmt.Println(A)
}
func initArray2() {
A := [...]int{1, 2, 3, 4}
fmt.Println(A)
}

The most surprising part might be the [...], one of many surprises that I got from Go. This actually means that you want an array, and not a slice. Indeed, removing the ... will return a slice instead.

But what is the difference exactly? That is a great question. Without getting into the internals of slices, which is how the difference is explained in the Go blog, the main difference is resizing. You can append to a slice and shrink a slice. Of course, resizing helps and dynamic size is important in a lot of data structures, which is why you should almost…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet