前往:使用自动返回值初始化地图 [英] Go: Initialize a map with automatic return values

查看:40
本文介绍了前往:使用自动返回值初始化地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在函数定义中声明了一个 map [string] string 返回值,那么在使用它之前是否必须先将其赋值,就像我在函数体中声明了它一样? http://play.golang.org/p/iafZbG2ZbY

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:运行时错误:分配给nil map中的条目

推荐答案

地图类型

未初始化映射的值为 nil .

使用内置函数 make 创建一个新的空映射值.

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

一个 nil 映射等效于一个空映射,不同之处在于没有元素可以是添加.

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

是的

这篇关于前往:使用自动返回值初始化地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆