Why doesn't Golang allow const maps?

后端 未结 2 407
萌比男神i
萌比男神i 2020-12-30 20:35

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

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


        
2条回答
  •  萌比男神i
    2020-12-30 21:37

    From 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 only numeric types, strings and bools can be constants, arrays, slices and maps aren't a numeric type.

提交回复
热议问题