What do we mean by allocate the map before we can store into it?

package main

import(
  "fmt"
)

func main(){
   var ages map[string]int     // Declaration 1 
   ages := make(map[string]int)     // Declaration 2
   ages["Ujjwal"] = 32

   fmt.Println(ages)
}

While going through the book I came across this line “You must allocate the map before you can store into it.” . If we comment out Declaration 2 and run this code. we got a error “panic: assignment to entry in nil map” . And if we comment out declaration 1 then out code run smoothly. I am not able to understood this “You must allocate the map before you can store into it.” statement in the context of above code.

When you declare a variable, you just do that, that is, you don’t initialize it. while if you use: = it is declared and initialized.
You can do the same with var if you do

var ages map [string] int = make (map [string] int)
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.