Home »
Golang
Create an Empty Map in Go
Last Updated : May 27, 2025
An empty map has no key-value pairs initially, but you can add elements dynamically by assigning values to new keys. Empty map can be created either using the make
literal or the make()
function.
Creating an Empty Map Using make()
The make()
function is the recommended way to create an empty map. Here, you must specify the key and value types.
Example
This example demonstrates how to create an empty map of type map[string]int
and add elements to it:
package main
import "fmt"
func main() {
marks := make(map[string]int) // Create an empty map
marks["Amit"] = 95
marks["Neha"] = 89
fmt.Println("Marks map:", marks)
}
When executed, this program outputs:
Marks map: map[Amit:95 Neha:89]
Creating an Empty Map with map Literal
You can also create an empty map using a literal syntax with no key-value pairs.
Example
This example shows how to create an empty map using {}
and then add elements:
package main
import "fmt"
func main() {
phoneBook := map[string]string{} // Empty map
phoneBook["John"] = "9876543210"
phoneBook["Alice"] = "9123456789"
fmt.Println("Phone Book:", phoneBook)
}
When executed, this program outputs:
Phone Book: map[Alice:9123456789 John:9876543210]
Empty Map vs nil Map
A map created using make()
or {}
is ready to use. But if you declare a map without initializing it, it becomes a nil
map and cannot be used until it's initialized.
Example
This example compares a nil map and an initialized map:
package main
import "fmt"
func main() {
var scores map[string]int // nil map
if scores == nil {
fmt.Println("scores is nil, initializing now...")
scores = make(map[string]int)
}
scores["Ravi"] = 88
fmt.Println("Scores:", scores)
}
When executed, this program outputs:
scores is nil, initializing now...
Scores: map[Ravi:88]
Exercise
Select the correct option to test your understanding of creating empty maps in Go.
- Which of the following correctly creates an empty map of type
map[string]int
?
- What is the initial value of an uninitialized map variable in Go?
- What happens if you try to add an element to a nil map?
Advertisement
Advertisement