This question already has an answer here:
I have a type A
that is basically a simple map:
type A map[int32]struct{}
Now, I would like to have a special value of this type to be able to treat it a bit differently. I thought that it would be smart to use nil
for this propose (additionally, this way, all non initialized variables of type A
would have this value, and this is also what I would like to have):
const s A = nil
But I got
const initializer cannot be nil
Sure I can accept this and refactor my program in dozens of different ways. But I'm still wondering why it's impossible to initialize const
to nil
? There must be an architectural reason but I don't see it.
(Note that I prefer to "rename" nil
instead of using it directly only because the name nil
is not very intuitive in my case.)
</div>
I believe that it is because you can only have constants of type boolean
, rune
, integer
, floating-point
, complex
, and string
. Docs: https://golang.org/ref/spec#Constants
Whereas nil
is a zero-value for types pointer
, interface
, map
, slice
, channel
and function
Docs: https://golang.org/ref/spec#The_zero_value
You can read more here https://blog.golang.org/constants