O'Reilly logo

Head First Go by Jay McGavren

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6 slices

Appending Issue

Images

We've learned we can't add more elements to an array. That's a real problem for our program, because we don't know in advance how many pieces of data our file contains. But that's where Go slices come in. Slices are a collection type that can grow to hold additional items — just the thing to fix our current program! We'll also see how slices can provide an easier way for users to provide data to all your programs, and how they can help you write functions that are more convenient to call.

Slices

There actually is a Go data structure that we can add more values to — it's called a slice. Like arrays, slices are made up of multiple elements, all of the same type. Unlike arrays, functions are available for slices that allow us to add extra elements onto the end.

To declare a variable that holds a slice, you type an empty pair of square brackets, followed by the type of elements the slice will hold.

Images

This is just like the syntax for declaring an array variable, except that you don't specify the size.

Images

Declaring a slice variable doesn't automatically create a slice. For that, you can call the built-in make function. You pass make the type of the slice you want to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required