Arrays & Slices

Duration: 15 min  •  Difficulty: Medium

In Go, there are two ways to store collections of data: Arrays and Slices. What's the difference?

1. Array (Rarely Used)

Arrays have a fixed size. If you create an array [5]int, you cannot adds a 6th element.

  • Pros: Memory efficient, fast.
  • Cons: Not flexible.
  • 2. Slice (Commonly Used)

    A Slice is a dynamic "window" into an array. Its size can change (expand or shrink).

  • Pros: Highly flexible.
  • Function: append() to add data.
  • When to use?

    In almost 99% of cases in Go, you will use a Slice. Use an Array only if you know for sure the number of items will never change (e.g., the 7 Days of the week).

    MAIN.GO
    package main
    import "fmt"
    func main() {
    // Array: FIXED size [2]
    var arr [2]int
    arr[0] = 100
    arr[1] = 200
    fmt.Println("Array:", arr)
    // Slice: DYNAMIC size [] (empty brackets)
    primes := []int{2, 3, 5, 7}
    fmt.Println("Initial Slice:", primes)
    // Adding new data to the slice using append
    primes = append(primes, 11)
    fmt.Println("New Slice:", primes)
    }