Go — Slices (basics)

Slices are very much similar to Arrays in Go but provide a much more powerful, and easier interface than arrays do. One of the main differences between slices and arrays in Go is that slices are only detailed by the items it contains, and not what they possibly could contain.

You can create an empty slice using the function: “make”. Note that even though the slice is initialized with 3 spots, it does not show these 3 spots:

Like arrays you can get and set the different items in the slice, and also see the length of the slice, just as you did with arrays:

Unlike arrays, slices have some more functionality which makes slices much more powerful than arrays.

One of these powerful functions is the “append” function. Append allows for, like the name suggests, appending values to the slice:

Slices can also be copied using the function: “copy”. Another way to copy a subsample of a slice is to use slice “slice” functionality. The slice functionality returns a new slice with the “sliced” items:

If you omit one of the numbers when slicing a slice, it will return all previous or latter items in the slice:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikolaj Johannes Skole Jensen

Fullstack developer living in Denmark. Experience with both Web- and App development.