Why can't we declare a map and fill it after in the const?

前端 未结 1 387
有刺的猬
有刺的猬 2021-01-29 08:40

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?<

相关标签:
1条回答
  • 2021-01-29 09:10

    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.

    0 讨论(0)
提交回复
热议问题