Arrays

Back

Loading concept...

📦 Arrays in Go: Your Personal Storage Boxes

Imagine you have a row of identical boxes on a shelf. Each box has a number (0, 1, 2, 3…) written on it, and each can hold exactly one toy. That’s an array in Go!


🎯 What is an Array?

An array is a fixed-size collection of items that are all the same type. Think of it like:

  • A carton of eggs (12 slots, each holds 1 egg)
  • A chocolate box (each slot = 1 chocolate)
  • Parking spaces in a row (each spot = 1 car)

Key idea: Once you create an array with 5 slots, it always has 5 slots. No more, no less!


📝 Array Declaration

Declaration means telling Go: “Hey, I want some boxes!”

The Recipe

var name [size]type
  • name = what you call your boxes
  • size = how many boxes
  • type = what goes inside

Examples

// 5 boxes for numbers
var scores [5]int

// 3 boxes for words
var names [3]string

// 4 boxes for true/false
var flags [4]bool

What happens? Go creates the boxes and fills them with zero values:

  • Numbers get 0
  • Strings get "" (empty)
  • Booleans get false
graph TD A["var scores [5]int"] --> B["scores"] B --> C["[0] = 0"] B --> D["[1] = 0"] B --> E["[2] = 0"] B --> F["[3] = 0"] B --> G["[4] = 0"]

🎨 Array Initialization

Initialization means putting toys in your boxes right away!

Method 1: Fill All Boxes

// All 4 values at once
colors := [4]string{
    "red",
    "blue",
    "green",
    "yellow",
}

Method 2: Let Go Count

Use ... and Go counts for you:

// Go figures out: "Oh, 3 items!"
fruits := [...]string{
    "apple",
    "banana",
    "cherry",
}
// fruits is now [3]string

Method 3: Specific Slots Only

// Put things in specific boxes
grades := [5]int{
    0: 90,  // box 0 = 90
    2: 85,  // box 2 = 85
    4: 88,  // box 4 = 88
}
// Result: [90, 0, 85, 0, 88]

Story Time: Think of it like numbered lockers. You can put your stuff in locker 0, skip 1, put in 2, skip 3, put in 4!


🔄 Array Iteration

Iteration means looking at each box, one by one.

Method 1: Classic For Loop

numbers := [4]int{10, 20, 30, 40}

for i := 0; i < len(numbers); i++ {
    fmt.Println("Box", i, "has", numbers[i])
}

Output:

Box 0 has 10
Box 1 has 20
Box 2 has 30
Box 3 has 40

Method 2: Range (The Easy Way!)

numbers := [4]int{10, 20, 30, 40}

for index, value := range numbers {
    fmt.Println("Box", index, "has", value)
}

Pro tip: Don’t need the index? Use _:

for _, value := range numbers {
    fmt.Println("Found:", value)
}
graph TD A["for range numbers"] --> B["Step 1: index=0, value=10"] B --> C["Step 2: index=1, value=20"] C --> D["Step 3: index=2, value=30"] D --> E["Step 4: index=3, value=40"] E --> F["Done!"]

🏢 Multidimensional Arrays

What if each box contains more boxes? That’s a multidimensional array!

2D Array: Grid of Boxes

Think of a tic-tac-toe board or a spreadsheet:

// 3 rows, 4 columns
var grid [3][4]int
Row 0: [0][0] [0][1] [0][2] [0][3]
Row 1: [1][0] [1][1] [1][2] [1][3]
Row 2: [2][0] [2][1] [2][2] [2][3]

Initialize a 2D Array

matrix := [2][3]int{
    {1, 2, 3},    // Row 0
    {4, 5, 6},    // Row 1
}

Visual:

    Col0  Col1  Col2
Row0:  1     2     3
Row1:  4     5     6

Access Elements

// Get row 1, column 2
value := matrix[1][2]  // = 6

// Set row 0, column 1
matrix[0][1] = 99

Loop Through 2D Array

matrix := [2][3]int{
    {1, 2, 3},
    {4, 5, 6},
}

for row := 0; row < 2; row++ {
    for col := 0; col < 3; col++ {
        fmt.Print(matrix[row][col], " ")
    }
    fmt.Println()
}

Output:

1 2 3
4 5 6

3D Array: Boxes Inside Boxes Inside Boxes!

// 2 layers, 3 rows, 4 columns
var cube [2][3][4]int

Think of it as 2 spreadsheets stacked on top of each other!

graph TD A["3D Array [2][3][4]int"] --> B["Layer 0"] A --> C["Layer 1"] B --> D["3x4 grid"] C --> E["3x4 grid"]

🌟 Quick Summary

Concept What It Does Example
Declaration Creates empty boxes var nums [5]int
Initialization Creates & fills boxes nums := [3]int{1,2,3}
Iteration Visits each box for i, v := range nums
Multidimensional Boxes inside boxes var grid [3][4]int

💡 Remember!

  1. Size is fixed - Arrays can’t grow or shrink
  2. Index starts at 0 - First box is [0], not [1]
  3. Same type only - All boxes hold the same kind of thing
  4. len() is your friend - Always use len(array) to get size

You’ve got this! Arrays are just numbered boxes in a row. Simple, predictable, and super useful! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.