Chapter 6

Data Structures

Arrays and structs

Arrays

Arrays are ordered, dynamic collections:

// Create arrays
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [42, "hello", true, 3.14]
nested = [[1, 2], [3, 4], [5, 6]]

Accessing Elements

fruits = ["apple", "banana", "cherry"]

// Index access (0-based)
print(fruits[0])  // "apple"
print(fruits[1])  // "banana"
print(fruits[2])  // "cherry"

// Nested arrays
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[0][0])  // 1
print(matrix[1][2])  // 6

Modifying Arrays

arr = [1, 2, 3]

// Update element
arr[0] = 100
print(arr)  // [100, 2, 3]

// Add element
arr.push(4)
print(arr)  // [100, 2, 3, 4]

// Remove last element
last = arr.pop()
print(last)  // 4
print(arr)   // [100, 2, 3]

Array Operations

arr = [1, 2, 3, 4, 5]

// Length
print(len(arr))  // 5

// Iteration
for (item in arr) {
    print(item)
}

// Sum elements
total = 0
for (num in arr) {
    total = total + num
}
print("Sum:", total)  // 15

Structs

Structs define custom data types with named fields:

// Define a struct
struct Person {
    name,
    age,
    city
}

// Create instances
alice = Person("Alice", 30, "Jakarta")
bob = Person("Bob", 25, "Bandung")

// Access fields
print(alice.name)  // "Alice"
print(alice.age)   // 30

// Modify fields
alice.age = 31
print(alice.age)   // 31

Structs with Methods

struct Rectangle {
    width,
    height
}

// Functions that work with structs
func area(rect) {
    return rect.width * rect.height
}

func perimeter(rect) {
    return 2 * (rect.width + rect.height)
}

r = Rectangle(10, 5)
print("Area:", area(r))           // 50
print("Perimeter:", perimeter(r)) // 30

Nested Structs

struct Address {
    street,
    city,
    country
}

struct Company {
    name,
    address,
    employees
}

addr = Address("Jl. Sudirman", "Jakarta", "Indonesia")
company = Company("TechCorp", addr, 100)

print(company.name)              // "TechCorp"
print(company.address.city)      // "Jakarta"
print(company.employees)         // 100

Working with Collections

Array of Structs

struct User {
    id,
    name,
    active
}

users = [
    User(1, "Alice", true),
    User(2, "Bob", true),
    User(3, "Charlie", false)
]

// Process users
for (user in users) {
    if (user.active) {
        print("Active user:", user.name)
    }
}

Building Data

// Build array dynamically
squares = []
for (i in Range(1, 6)) {
    squares.push(i * i)
}
print(squares)  // [1, 4, 9, 16, 25]

// Accumulate results
struct Result {
    value,
    squared
}

results = []
for (i in Range(1, 4)) {
    results.push(Result(i, i * i))
}

for (r in results) {
    print(r.value, "squared is", r.squared)
}