rxmnnxfpvg
rxmnnxfpvg

Reputation: 30993

Go: Initialize a map with automatic return values

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

Upvotes: 9

Views: 8013

Answers (1)

peterSO
peterSO

Reputation: 166598

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.

Upvotes: 19

Related Questions