Golang为什么不允许const映射? [英] Why doesn't Golang allow const maps?

查看:479
本文介绍了Golang为什么不允许const映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个如下的常量映射:

I would like to create a constant map like the following:

const (
    running = map[string]string{
        "one": "ONE",
        "two": "TWO",
    }
)

但是无论何时我遇到以下错误:

however whenever I do I get the following error:

const initializer map[string]string literal is not a constant

为什么会这样,为什么Golang不会像对待其他变量一样对待它们?

Why is this the case, why does Golang not treat them like any other variable?

推荐答案

来自 https://golang.org /ref/spec#常量:

常量值由符文,整数,浮点数, 虚数或字符串文字,表示常量的标识符, 常量表达式,其结果为常量的转换,或者 一些内置函数(例如unsafe.Sizeof)的结果值 适用于任何值,上限或上限,适用于某些表达式,实数和 imag适用于复数常数,适用于数字 常数.

A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants.

tl; dr仅数字类型,字符串和布尔值可以是常量,数组,切片和映射不是数字类型.

tl;dr only numeric types, strings and bools can be constants, arrays, slices and maps aren't a numeric type.

这篇关于Golang为什么不允许const映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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