英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论