gpt4 book ai didi

dictionary - 为什么 Golang 不允许 const 映射?

转载 作者:IT老高 更新时间:2023-10-28 13:02:45 25 4
gpt4 key购买 nike

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

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

但是每当我这样做时,我都会收到以下错误:

const initializer map[string]字符串字面量不是常量

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

最佳答案

来自 https://golang.org/ref/spec#Constants :

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 只有数字类型,字符串和 bool 值可以是常量,数组、 slice 和映射不是数字类型。

关于dictionary - 为什么 Golang 不允许 const 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37984320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com