Go Maps:
Maps in Go are unordered collections of key-value pairs. They are similar to dictionaries in Python or objects in JavaScript.
1. Declaring and Initializing a Map
Use the make function or a map literal to create a map:
go
package main
import "fmt"
func main() {
ages := make(map[string]int)
ages["Alice"] = 30
ages["Bob"] = 25
fmt.Println(ages)
}2. Map Literals
You can also define a map using a literal:
go
func main() {
colors := map[string]string{
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
}
fmt.Println(colors["green"])
}3. Checking for Key Existence
Use the second return value to check if a key exists:
go
func main() {
scores := map[string]int{"Tom": 90}
val, exists := scores["Tom"]
if exists {
fmt.Println("Tom's score:", val)
} else {
fmt.Println("Tom not found")
}
}4. Deleting a Key
Use the delete function to remove a key:
go
func main() {
users := map[string]bool{"admin": true, "guest": false}
delete(users, "guest")
fmt.Println(users)
}5. Iterating Over a Map
Use a for loop with range to iterate over a map:
go
func main() {
countryCodes := map[string]string{
"US": "United States",
"FR": "France",
"JP": "Japan",
}
for code, country := range countryCodes {
fmt.Println(code, ":", country)
}
}