Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Initialize a map with automatic return values

Tags:

go

If I declare a map[string]string return value in a function definition, do I have to make it before using it, just like if I had instead declared it in the function body? http://play.golang.org/p/iafZbG2ZbY

package main

import "fmt"

func fill() (a_cool_map map[string]string) {
    // This fixes it: a_cool_map = make(map[string]string)
    a_cool_map["key"] = "value"
    return
}
func main() {
    a_cool_map := fill()
    fmt.Println(a_cool_map)
}

panic: runtime error: assignment to entry in nil map

like image 574
atp Avatar asked Oct 19 '12 00:10

atp


1 Answers

Map types

The value of an uninitialized map is nil.

A new, empty map value is made using the built-in function make.

A nil map is equivalent to an empty map except that no elements may be added.

Yes.

like image 107
peterSO Avatar answered Oct 20 '22 00:10

peterSO