为什么我们不能声明一个映射并在const中填充它? [英] Why can't we declare a map and fill it after in the const?

查看:143
本文介绍了为什么我们不能声明一个映射并在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屋!

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