Ad space (banner)
๐ŸนGo Lessons
Lesson 7 / 68

Slices (Arrays)

In this lesson you will learn the basics of slices (variable-length arrays) in Go so you can handle several pieces of data together. This is for anyone searching for "Go slices how to use".

An array is like a shelf of numbered drawers. In Go a variable-length array is called a slice. range takes the items out one at a time.

The sample code builds a slice with fruits := []string{"apple", "orange", "grape"} and prints each item with its number, taking the index and the element together with for i, fruit := range fruits. Go provides slices, whose elements can be freely added and removed, alongside fixed-length arrays.

A common stumbling block for beginners is that a slice holds a reference to an underlying array. Assigning a slice to another variable shares the same data, so changing one can affect the other - the copying behaviour sometimes needs care.

In real-world development slices are used almost everywhere in preference to fixed-length arrays, making them the basic data structure you will meet constantly in Go code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)