To create a map with initial key-value pairs in Go, you can use the map literal syntax. This creates a new map object with predefined key-value pairs.
We can create a map in Go with initial key-value pairs using the map literal syntax, which initializes a map with predefined key-value pairs.
For example,
myMap
. This variable will hold our map with initial key-value pairs.myMap
variable. In this example, the map has string keys and integer values.package main
import "fmt"
func main() {
// Declare a map with initial key-value pairs
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Operations on the map
for key, value := range myMap {
fmt.Printf("%s: %d\n", key, value)
}
}
one: 1 two: 2 three: 3
We can create a map in Go with initial key-value pairs of different types using the map literal syntax.
For example,
studentGrades
. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).studentGrades
variable. In this example, the map has string keys and rune values representing grades.package main
import "fmt"
func main() {
// Declare a map with initial key-value pairs
studentGrades := map[string]rune{
"Alice": 'A',
"Bob": 'B',
"Charlie": 'C',
}
// Operations on the map
for key, value := range studentGrades {
fmt.Printf("%s: %c\n", key, value)
}
}
Alice: A Bob: B Charlie: C
We can create a map in Go with initial key-value pairs where keys are integers and values are floats using the map literal syntax.
For example,
productPrices
. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are floats (prices).productPrices
variable. In this example, the map has integer keys and float64 values.package main
import "fmt"
func main() {
// Declare a map with initial key-value pairs
productPrices := map[int]float64{
101: 29.99,
102: 39.99,
103: 49.99,
}
// Operations on the map
for key, value := range productPrices {
fmt.Printf("Product %d: $%.2f\n", key, value)
}
}
Product 101: $29.99 Product 102: $39.99 Product 103: $49.99
In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in Go language with well detailed examples.