Learn Go · 4/18

Core Data Structures: Grouping Data

7 min read

Core Data Structures: Grouping Data 📊

Welcome! So far, you've likely been working with single pieces of data—a number here, a string there. But what happens when you need to handle a collection of data? Imagine you're building a feature to list all users of your application. You wouldn't create a separate variable for each user, like user1, user2, user3, and so on. That would be a chaotic mess! This is where Go's core data structures for grouping data come to the rescue. They allow us to store and manage collections of data efficiently.


Arrays: Fixed-Size Collections 📏

The Problem: Imagine you're building a simple calendar application and you need to store the names of the days of the week. You know there will always be exactly seven days. How can you store this fixed-size list of data in an ordered way?

The Solution: An array is a fundamental data structure that stores a fixed-size sequence of elements of the same type. Think of it as a numbered row of boxes, where each box can hold the same type of item.

In Go, an array's size is part of its type. This means an array that can hold 5 integers ([5]int) is a different type from an array that can hold 6 integers ([6]int). This fixed-size nature makes them very predictable and memory-efficient.

Declaring an Array:

Here's how you declare an array in Go:

go
var a [3]int // Declares an array of 3 integers, initialized to their zero value (0 for int)

You can also declare and initialize an array at the same time:

go
days := [7]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

Accessing Elements:

You can access elements in an array using their index, which starts at 0.

go
firstDay := days[0] // "Monday"
thirdDay := days[2] // "Wednesday"

Under the Hood: Arrays in Go are value types. When you assign an array to a new variable or pass it to a function, a complete copy of the array is created. This can be inefficient for large arrays! 😬

Industry Use: Arrays are used when you know the exact number of elements you need to store, and that number won't change. For example, storing the RGB values of a color (always 3 values) or the months in a year (always 12).


Slices: Dynamic and Powerful Sequences 🏄‍♀️

The Problem: Arrays are great, but what if you don't know the size of your collection beforehand? Imagine you're building a shopping cart. You have no idea how many items a user will add. An array with a fixed size just won't work here.

The Solution: A slice is a more flexible and powerful way to handle sequences of data. It's a view or a "slice" of an underlying array. Slices can be resized, which is incredibly useful.

Creating a Slice:

You can create a slice in a few ways. A common way is using a slice literal, which looks a lot like an array literal but without the size:

go
// A slice of strings
shoppingList := []string{"milk", "bread", "eggs"}

You can also create a slice from an existing array:

go
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4] // Creates a slice from the 2nd to the 4th element: [3, 5, 7]

Working with Slices:

The real power of slices comes from their dynamic nature. You can add new elements to a slice using the append function.

go
shoppingList = append(shoppingList, "cheese")
// shoppingList is now ["milk", "bread", "eggs", "cheese"]

Under the Hood: A slice is a small data structure that holds three pieces of information:

  1. A pointer to the underlying array.
  2. The length of the slice (the number of elements it contains).
  3. The capacity of the slice (the number of elements it can hold from the start of the slice to the end of the underlying array).

When you append to a slice and it exceeds its capacity, Go will automatically create a new, larger underlying array and copy the elements over. It's like your backpack magically getting bigger when you buy too many souvenirs on vacation! 🎒

Industry Use: Slices are one of the most common data structures in Go. You'll use them everywhere you need a dynamic list of items, such as storing a list of user records from a database, handling items in a shopping cart, or managing a queue of tasks.


Maps: Key-Value Associations 🔑

The Problem: Let's say you're building a system to store user information. You want to look up a user's age by their name. With an array or slice, you'd have to search through the entire list to find the right user. That's slow and inefficient.

The Solution: A map is a data structure that stores a collection of key-value pairs. This allows for incredibly fast lookups, insertions, and deletions based on the key. Think of it like a dictionary where you can quickly find the definition (value) by looking up the word (key).

Creating a Map:

You can create a map using the make function or a map literal.

go
// Using make
userAges := make(map[string]int)

// Using a map literal
userAges := map[string]int{
    "Alice": 30,
    "Bob":   25,
}

Working with Maps:

You can add or update key-value pairs easily:

go
userAges["Charlie"] = 35 // Add a new user
userAges["Alice"] = 31   // Update Alice's age

Accessing a value is just as simple:

go
alicesAge := userAges["Alice"] // 31

To delete a key-value pair, use the delete function:

go
delete(userAges, "Bob")

When you access a key that doesn't exist, you'll get the zero value for the value type (e.g., 0 for int, "" for string). To check if a key actually exists, you can use a two-value assignment:

go
age, ok := userAges["David"]
if ok {
    // David exists
} else {
    // David does not exist
}

Industry Use: Maps are extremely common for things like caching data, storing configuration settings, and representing JSON objects. Any time you need to quickly look up a value based on a unique identifier, a map is likely the right tool for the job.


Iterating over Collections using 'range' 🚶‍♂️

The Problem: You have a collection of data—an array, a slice, or a map—and you need to do something with each element. How can you easily go through them one by one?

The Solution: Go provides a special keyword called range that makes iterating over collections clean and simple.

Using range with Slices and Arrays:

The range keyword, when used with a slice or array in a for loop, returns two values on each iteration: the index and a copy of the element at that index.

go
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
    // `index` is the position, `fruit` is the value
}

If you only need the value and not the index, you can use the blank identifier _:

go
for _, fruit := range fruits {
    // `fruit` is the value
}

Using range with Maps:

When used with a map, range returns the key and the value for each pair.

go
userAges := map[string]int{
    "Alice": 30,
    "Bob":   25,
}

for name, age := range userAges {
    // `name` is the key, `age` is the value
}

An Interesting Fact: The order of iteration over a map is not guaranteed! If you need to iterate over a map in a specific order, you'll need to get the keys, sort them, and then iterate through the sorted keys to access the map values. This is an intentional design choice in Go to prevent developers from relying on a specific insertion order.

Industry Use: The for...range loop is the standard and most idiomatic way to iterate over collections in Go. Its simplicity and readability make it a favorite among Go developers.


📚 Further Reading & References

Challenge

Challenge: Process E-commerce Sales Data

You are tasked with creating a function to process a batch of sales transactions for an e-commerce platform. This function will update product inventory and calculate the total revenue generated for each product category.

Your Task:

Implement the processSales function. This function receives two arguments:

  1. inventory: A map where keys are product IDs (string) and values are the current stock levels (int).
  2. sales: A slice of sales transactions. Each transaction is represented as a map[string]interface{} containing a productID (string), quantity (int), price (float64), and category (string).

Function Requirements:

  1. Create a new map to store the total revenue for each category.
  2. Iterate over the sales slice using a for...range loop.
  3. For each sale transaction:
    a. Update the inventory map by subtracting the sold quantity from the correct product's stock.
    b. Calculate the revenue for the transaction (quantity * price).
    c. Add this revenue to the corresponding category's total in your new revenue map. If a category does not exist in the map yet, it should be added.
  4. The function must return two values: the modified inventory map and the newly created category revenue map.

Expected result

Your processSales function should correctly modify the inventory map and create a new categoryRevenue map with the calculated totals.

Based on the provided initial data, the returned maps should have the following final states:

1. Updated Inventory Map:

json
{
  "P001": 90,
  "P002": 47,
  "P003": 68
}

2. Category Revenue Map:

json
{
  "Books": 139.93,
  "Electronics": 1499.97,
  "Home Goods": 999.9
}

(Note: The order of keys in the returned maps does not matter.)

go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.