How to beautifully and correctly initialize a map in Go: make or literal?
Hello everyone! I've just started learning Go and encountered confusion over what seems like a simple question. How to properly initialize a map (dictionary)?\n\nI see different options in code, and I can't understand which one is considered "correct" or "beautiful" from the Go community's perspective.\n\nFor example, I can declare a map like this:\n
var m map[string]int\nBut if I try to write a value to it immediately after declaration:\nm["key"] = 10 // panic: assignment to entry in nil map\nI get a panic! It turns out the map needs to be initialized.\n\nI know two ways to do this:\n\n1. Using the make function:\nm := make(map[string]int)\nm["key"] = 10\n\n2. Using a literal (empty or with data):\nm := map[string]int{}\nm["key"] = 10\n// or with No answers yet.
Log in to leave an answer
Blogs