为什么我们不能声明一个映射并在const中填充它? [英] 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] =路径[Smith] [theFather] +Junior
)
常量被称为常量出于某种原因:您希望它们只是:常量。
类型定义您可以对该类型的值执行哪些操作。 Go中的映射类型不是常量,您可以在其创建后更改其键值对,所以你不能有 map
常量。
选择常量的调色板常量:
有布尔常量,符文常量,整数常量,浮点常量,复常量和字符串常量。
请参阅相关问题:声明一个常量数组
解决方法很简单:将其声明为变量而不是常量。
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"
)
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: Declare a constant array
Workaround is simple: declare it to be a variable instead of a constant.
这篇关于为什么我们不能声明一个映射并在const中填充它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!