1. Introduction
Maps in Go are powerful data structures that associate keys with values. Unlike slices or arrays, maps store data in key-value pairs for quick lookup and retrieval. This blog post will guide you through declaring and initializing a map in Go.
Definition
A map is a collection type that associates unique keys with values. In Go, a map is unordered, and its keys must be of a type that is comparable (like integers, strings, etc.), while the values can be of any type.
2. Program Steps
1. Declare a map using the var keyword.
2. Initialize the map using the make function.
3. Declare and initialize a map using a map literal.
4. Access and print elements of the map.
3. Code Program
package main
import "fmt"
func main() {
// Step 1: Declare a map using the var keyword
var colors map[string]string
// Step 2: Initialize the map using the make function
colors = make(map[string]string)
// Step 3: Declare and initialize a map using a map literal
// Directly initializing a map with key-value pairs
fruits := map[string]string{
"apple": "green",
"banana": "yellow",
}
// Adding key-value pairs to the map
colors["red"] = "#FF0000"
colors["blue"] = "#0000FF"
colors["green"] = "#00FF00"
// Step 4: Access and print elements of the map
fmt.Println("Color codes:")
for color, code := range colors {
fmt.Printf("%s: %s\n", color, code)
}
fmt.Println("\nFruit colors:")
for fruit, color := range fruits {
fmt.Printf("%s: %s\n", fruit, color)
}
}
Output:
Color codes: red: #FF0000 blue: #0000FF green: #00FF00 Fruit colors: apple: green banana: yellow
Explanation:
1. package main - Defines the main package.
2. import "fmt" - Imports the Format package, used for printing formatted output.
3. The colors map is declared using the var keyword and then initialized using make to create a map where both keys and values are strings.
4. The fruits map is declared and initialized with a map literal, which sets up the initial key-value pairs at the time of creation.
5. The colors map is populated with three key-value pairs, each representing a color name and its corresponding hex code.
6. Using for loops with range over colors and fruits, the program prints out each key-value pair.
7. The output shows the contents of both colors and fruits, demonstrating two different ways to declare and initialize maps in Go.
Comments
Post a Comment