为什么我们不能在const中声明一个map,并在之后填充它呢?

huangapple go评论89阅读模式
英文:

Why can't we declare a map and fill it after in the const?

问题

为什么……为什么会出现错误呢?
是因为它重新分配了地图以允许扩展,还是因为编译器解析器不能处理这些情况?

const (
    paths = &map[string]*map[string]string {
        Smith: {
            "theFather": "John",
        },
    }
    paths["Smith"]["theSon"] = paths["Smith"]["theFather"] + " Junior"
)

请注意,我只提供代码的翻译,不会回答关于翻译的问题。

英文:

Just why... why does this generate an error?
Is it because it reallocates the map to allow the extension or just because the compiler parser is not meant to handle these cases?

const (
    	paths = &map[string]*map[string]string {
		    Smith: {
			    "theFather": "John",
		    },
	    }
	    paths["Smith"]["theSon"] = paths["Smith"]["theFather"] + " Junior"
)

答案1

得分: 2

常量 之所以被称为“常量”,是因为你期望它们是不变的。

类型定义了你可以对该类型的值执行哪些操作。Go 中的 map 类型不是常量,你可以在创建后更改其键值对,因此你不能有 map 常量。

你可以从规范中的“常量”部分选择常量的“调色板”:

布尔常量符文常量整数常量浮点数常量复数常量字符串常量

参考相关问题:https://stackoverflow.com/questions/13137463/declare-a-constant-array/29365828#29365828

解决方法很简单:将其声明为变量而不是常量。

英文:

Constants are called constants for a reason: you expect them to be just that: constant.

The type defines what operations you may perform on a value of that type. The map type in Go is not constant, you can change its key-value pairs after its creation, so you cannot have map constants.

Your "palette" to choose constants from is defined in the Spec: Constants:

> There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants.

See related question: https://stackoverflow.com/questions/13137463/declare-a-constant-array/29365828#29365828

Workaround is simple: declare it to be a variable instead of a constant.

huangapple
  • 本文由 发表于 2017年3月1日 18:49:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/42529691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定