Arrays & Dynamic Slices

🐹 Go Language Lesson 6 Intermediate

In Go, arrays are fixed in size. Slices are dynamic, resizing windows built over arrays that form the core data container in Go.

1 Slices as Dynamic Windows (Length vs. Capacity)

Go distinguishes between these two structures:

  • Array: Fixed-size container: `var arr [5]int`. The array size is part of its type definition, making it rigid.
  • Slice: Dynamically resizable wrapper pointing to an underlying array: `var s []int`. Slices track:
    • Length: The number of active elements inside the slice.
    • Capacity: The maximum number of elements the slice can hold before it must reallocate memory.

Adding elements is done using the built-in **`append()`** function: `slice = append(slice, 10)`.

2 Slice Manipulations

Let's run a program demonstrating slices, slice operators, and dynamic appends:

Go — Slices and Operations ▶ Run Code
package main

import "fmt"

func main() {
    // Declare slice
    numbers := []int{10, 20, 30}
    fmt.Printf("Len: %d, Cap: %d, Data: %v\n", len(numbers), cap(numbers), numbers)

    // Dynamic append (resizes memory internally if cap is exceeded)
    numbers = append(numbers, 40)
    fmt.Printf("After Append - Len: %d, Cap: %d, Data: %v\n", len(numbers), cap(numbers), numbers)

    // Slice operator: slice[start:end] (excludes element at end index)
    subSlice := numbers[1:3] // references indices 1 and 2
    fmt.Println("Sub-slice: ", subSlice)
}
3 Code Challenge
Challenge: Write a program that creates a slice of strings containing product names. Use a loop to iterate through the slice and print both the index and value of each item. Use the range keyword to simplify the loop.