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.
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:
For more details, check the official Go documentation: Go Documentation
arrays_slices_maps.go
in your Go project.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)
}
go run arrays_slices_maps.go
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]
🚀 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! ☕😊