RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 8: Arrays and Slices – Like Lists You Can Grow and Shrink 🧺

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

Imagine you have a tray with 5 cups. You can’t change the tray — it's stuck with 5 slots. That’s an array.

But what if you want a flexible basket where you can toss in more or fewer items? That’s a slice.

Here’s how you make an array in Go:

var numbers [3]int
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
  • [3]int → means "an array of 3 integers"

  • You can’t make it 4 later. It's locked.

Print it:

fmt.Println(numbers)

Output:

[10 20 30]

In Go, you’ll almost always use slices instead. They’re like arrays but better.

Make a slice like this:

fruits := []string{"apple", "banana", "mango"}
fmt.Println(fruits)
  • No size in the [] — that means it's a slice.

  • You can add, remove, or resize it.

Use append():

fruits := []string{"apple", "banana"}
fruits = append(fruits, "orange")
fmt.Println(fruits)

Output:

[apple banana orange]

append always returns a new slice, so you must assign it back.

for i, fruit := range fruits {
  fmt.Println(i, fruit)
}

Or ignore the index:

for _, fruit := range fruits {
  fmt.Println(fruit)
}

You can take parts of a slice:

fruits := []string{"apple", "banana", "mango", "orange"}
fmt.Println(fruits[1:3]) // banana, mango

fruits[1:3] = from index 1 up to (but not including) index 3

Two things slices have:

  • len(slice) → how many items

  • cap(slice) → how many items it can hold before needing to grow

fmt.Println(len(fruits)) // 4
fmt.Println(cap(fruits)) // usually 4, but can be more after appends

You usually don't need cap(), but it's good to know.

Go doesn’t have built-in remove(). You have to slice around it:

fruits := []string{"apple", "banana", "mango"}
index := 1 // remove "banana"
fruits = append(fruits[:index], fruits[index+1:]...)
fmt.Println(fruits)

Output:

[apple mango]
  • Arrays = fixed-size boxes

  • Slices = growable lists (use these!)

  • Use append() to add

  • Use slice[start:end] to chop

  • Loop with for range

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.