DEV Community

Cover image for πŸ”₯ Arrays vs Slices in Go (Explained in the Simplest Way)
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

πŸ”₯ Arrays vs Slices in Go (Explained in the Simplest Way)

If you just started learning Go, one thing will confuse you quickly:

πŸ‘‰ Arrays vs Slices

They look similar… but behave very differently.

Let’s break it down in the simplest way possible πŸ‘‡


πŸ“¦ What is an Array?

An array is a fixed-size collection.

numbers := [3]int{1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • Size is fixed
  • Cannot grow or shrink
  • Rarely used in real-world Go apps

πŸ”„ What is a Slice?

A slice is a dynamic version of an array.

numbers := []int{1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • Size is dynamic
  • Can grow using append
  • Used almost everywhere in Go

⚑ Adding Data (Only Works with Slice)

numbers := []int{1, 2, 3}

numbers = append(numbers, 4)
Enter fullscreen mode Exit fullscreen mode

Now:

[1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

🧠 Under the Hood (Important Concept)

A slice is:

  • Pointer to an array
  • Length
  • Capacity

Think of it like:
πŸ‘‰ β€œA flexible view on top of an array”


πŸ” Slice Example with Capacity

numbers := make([]int, 2, 5)

fmt.Println(len(numbers)) // 2
fmt.Println(cap(numbers)) // 5
Enter fullscreen mode Exit fullscreen mode

❗ Common Mistake

arr := [3]int{1,2,3}
arr = append(arr, 4) // ❌ ERROR
Enter fullscreen mode Exit fullscreen mode

Why?
πŸ‘‰ Because arrays are fixed size


πŸ”₯ Real-World Use Case

When building APIs:

users := []string{}

users = append(users, "Ahmed")
users = append(users, "John")
Enter fullscreen mode Exit fullscreen mode

Dynamic data = slices βœ…


🧭 When to Use What?

Feature Array Slice
Size Fixed Dynamic
Usage Rare Common
Flexibility ❌ βœ…

πŸ‘‰ In 95% of cases β†’ use slice


πŸ’¬ Final Thought

If you understand slices, you understand how Go manages data internally.

This is a foundational conceptβ€”don’t skip it.


πŸš€ Coming Next

Next post:
πŸ‘‰ Structs in Go (this is where real backend modeling starts)


golang #backend #programming #webdev #devto

Top comments (0)