Exercise 4: Arrays, Slices, and Maps in Go

In this exercise, you'll learn how to use arrays, slices, and maps in Go. These structures are essential for handling collections of data efficiently.

Understanding Arrays, Slices, and Maps in Go

In Go, arrays are fixed-size collections. Once declared, their size cannot change.

Slices, on the other hand, are dynamic arrays that can grow or shrink as needed using the append() function.

Maps are key-value data structures, similar to dictionaries in Python or objects in JavaScript.

Comparison with other languages:

  • Arrays: In Go, arrays have a fixed size, unlike Python lists or JavaScript arrays, which are dynamic.
  • Slices: Unlike Python lists, Go slices give more control over memory management.
  • Maps: Go maps function similarly to Python dictionaries and JavaScript objects.

For more details, check the official Go documentation: Go Documentation

Instructions:

  • 1️⃣ Create a file named arrays_slices_maps.go in your Go project.
  • 2️⃣ Declare a fixed-size array, a dynamic slice, and a map.
  • 3️⃣ Print the content of these structures to the console.
package main

import "fmt"

func main() {
    // 1. Array
    var array [3]int = [3]int{1, 2, 3}
    fmt.Println("Array:", array)
    
    // 2. Slice
    var slice = []string{"Go", "Rust", "Python"}
    slice = append(slice, "JavaScript")  // Add an element
    fmt.Println("Slice after append:", slice)
    
    // 3. Map
    var myMap = make(map[string]int)
    myMap["Go"] = 1
    myMap["Rust"] = 2
    fmt.Println("Map example:", myMap)
}
  • 4️⃣ Run the program using the command: go run arrays_slices_maps.go

Code Explanation:

1️⃣ var array [3]int = [3]int{1, 2, 3} : Declares a fixed-size array with 3 elements.

2️⃣ var slice = []string{"Go", "Rust", "Python"} : Declares a dynamic slice and appends an element using append().

3️⃣ var myMap = make(map[string]int) : Creates an empty map of type string → int. Elements are added using myMap["Go"] = 1.

4️⃣ fmt.Println() : Prints the values of our array, slice, and map to the console.

✅ If your program is correct, running it should display the following output:

Array: [1 2 3]

Slice after append: [Go Rust Python JavaScript]

Map example: map[Go:1 Rust:2]

← Previous Exercise Next Exercise →

🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee