DEV Community

Andi
Andi

Posted on

Go (Golang) Basic - Data Collections: Array, Slice, and Map

Storing More Than One Piece of Data

So far, we've learned how to store single pieces of information in variables. But what happens when you need to manage a list of items, like a grocery list, or a collection of user settings? Storing each one in a separate variable would be a nightmare!

This is where data collections come in. Go provides powerful, built-in types for managing groups of data. In this part, we'll focus on the two you'll use 99% of the time: Slices and Maps.

1. The Slice: Your Go-To Dynamic List

A slice is the most common collection type you'll use in Go. Think of it as a dynamic, flexible list that can grow or shrink as needed.

Analogy: A shopping list. You can start with a few items and add more as you think of them. The order of the items matters.

Creating and Using a Slice

Let's see it in action.

package main

import "fmt"

func main() {
    // Creating a slice of strings with some initial data
    fruits := []string{"Apple", "Banana", "Cherry"}
    fmt.Println("Initial fruits:", fruits)

    // Adding a new item to the slice using append()
    fruits = append(fruits, "Orange")
    fmt.Println("After adding Orange:", fruits)

    // Accessing an element by its index (starts from 0)
    fmt.Println("The first fruit is:", fruits[0])
}
Enter fullscreen mode Exit fullscreen mode

Key points about Slices:

  • The syntax []string means "a slice of strings".
  • append() is the built-in function to add elements to a slice.
  • You access elements using an index, starting from 0.

2. The Map: A Key-Value Collection

A map is a collection of key-value pairs. It's incredibly useful when you want to look up a value based on a unique identifier (the key).

Analogy: A phone's contact list. You use a unique key (the person's name) to look up their value (their phone number). The order of contacts doesn't really matter.

Creating and Using a Map

Maps are perfect for things like configuration or user profiles.

package main

import "fmt"

func main() {
    // Creating a map where the key is a string and the value is a string
    userProfile := map[string]string{
        "name":    "Budi",
        "email":   "budi@email.com",
        "country": "Indonesia",
    }
    fmt.Println("User profile:", userProfile)

    // Accessing a value by its key
    fmt.Println("User's name is:", userProfile["name"])

    // Adding or updating a value
    userProfile["city"] = "Jakarta"
    fmt.Println("After adding city:", userProfile)

    // Deleting a key-value pair
    delete(userProfile, "country")
    fmt.Println("After deleting country:", userProfile)
}
Enter fullscreen mode Exit fullscreen mode

Key points about Maps:

  • The syntax map[string]string means "a map with string keys and string values".
  • The order of elements in a map is not guaranteed.
  • You use the key to add, retrieve, or delete data.

Tentu, ini bagian kedua dan terakhir dari draf artikel Bagian 5 yang sudah direvisi.

Draf Artikel Bagian 5 (Revisi, 2/2)

3. The Map: A Key-Value Collection

While slices are great for ordered lists, sometimes you need to look up data based on a unique identifier, not its position. For this, we use a map. A map is a collection of key-value pairs.

Analogy: A phone's contact list. You use a unique key (the person's name) to look up their value (their phone number). The order of contacts doesn't really matter.

Creating and Using a Map

Maps are perfect for things like configuration, user profiles, or any data where you need fast lookups.

package main

import "fmt"

func main() {
    // Creating a map where the key is a string and the value is a string
    userProfile := map[string]string{
        "name":    "Budi",
        "email":   "budi@email.com",
        "country": "Indonesia",
    }
    fmt.Println("User profile:", userProfile)

    // Accessing a value by its key
    fmt.Println("User's name is:", userProfile["name"])

    // Adding or updating a value is done the same way
    userProfile["city"] = "Jakarta"
    fmt.Println("After adding city:", userProfile)

    // Deleting a key-value pair using delete()
    delete(userProfile, "country")
    fmt.Println("After deleting country:", userProfile)
}
Enter fullscreen mode Exit fullscreen mode

Key points about Maps:

  • The syntax map[string]string means "a map with string keys and string values".
  • The order of elements in a map is not guaranteed.
  • You use the key ([]) to add, retrieve, or delete() data.

Array vs. Slice vs. Map: Which One to Use?

Here's a quick guide:

  • Use an Array when you know exactly how many items you'll have, and that number will never change (very rare).
  • Use a Slice for almost everything else that is a list of items. It's the default choice for lists in Go.
  • Use a Map when you need to store data that should be accessed by a unique identifier, not by its position in a list.

Conclusion

You've now learned how to manage groups of data in Go! You understand the difference between a rigid Array, a flexible Slice, and a lookup-based Map. These three data structures are the foundation for building any complex application.

In the next part, we'll learn how to make our code "think" and make decisions using conditional logic with if and switch. See you there!

Top comments (0)