Constant map

19,498 views
Skip to first unread message

Joan Miller

unread,
Mar 23, 2010, 11:17:06 AM3/23/10
to golang-nuts
Why is not possible to create a constant map?

const mapArch = map[string] string {
"foo": "1",
"bar": "2",
}

chris dollin

unread,
Mar 23, 2010, 11:28:30 AM3/23/10
to Joan Miller, golang-nuts
Go only allows numbers & strings to be const'ed. A map isn't
a number or string.

The consequences of allowing const map (or const pretty much
any structured value) are more complicated than you might
expect. I can see why the Go authors decided that the game
wasn't worth the candle. For example, you're pretty much forced,
I think, to have two kinds of pointer -- pointer to X and pointer to
immutable X -- with conversion rules. And at least two kinds of
slice, one where you can update the base array and one where
you can't. And of course two kinds of map.

--
Chris "allusive" Dollin

chris dollin

unread,
Mar 23, 2010, 11:47:25 AM3/23/10
to Joan Miller, golang-nuts
On 23 March 2010 15:28, chris dollin <ehog....@googlemail.com> wrote:
Go only allows numbers & strings to be const'ed.

Wrong again. I could have /sworn/ that was in the spec last time I
looked. It seems to imply it: the sections on constants and constant
expressions only talk about numbers, strings, and booleans as far
as I can see, but I wrote the following code:

  package c

  type Spoo int

  const spoo = Spoo(17)

  const oops = int(spoo)

and the compiler was happy. Is the compiler over-lax, the spec
not sufficiently illustrative (for me), or what?

--
Chris "allusive" Dollin

Ian Lance Taylor

unread,
Mar 23, 2010, 12:27:32 PM3/23/10
to chris dollin, Joan Miller, golang-nuts
chris dollin <ehog....@googlemail.com> writes:

spoo and oops are being declared using constant declarations. A
constant declaration permits using a constant expression. A constant
expression permits any constant operand. In the expression
"int(spoo)", "spoo" is a constant operand by definition, because it is
declared using a const declaration. That alternative is explicitly
listed in the "Constants" section: "an identifier denoting a
constant." So it all seems more or less OK to me.

Ian

chris dollin

unread,
Mar 23, 2010, 12:52:54 PM3/23/10
to Ian Lance Taylor, Joan Miller, golang-nuts

I remembered some of this on the way home, so I apologise for
thinking this was something new. (Specifically I remembered
the const example with iota and a named type -- which I've even
/used/.)

The thing that was being non-obvious to me was that a type
expression counted as a constant when being used as a function,
because I think of the function expression part of an application as
one of the operands. That was just me and the end of the working
day.

--
Chris "oer-coffeed or undercoffeed or both" Dollin
Reply all
Reply to author
Forward
0 new messages