0

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.)

Boann
  • 48,794
  • 16
  • 117
  • 146
vonaka
  • 913
  • 1
  • 11
  • 23
  • 2
    Even if a const initializer could be nil, your A cannot be const. Const in Go works different. Read https://blog.golang.org/constants and the language spec. – Volker Aug 19 '19 at 11:42
  • OK, thanks @Volker, it makes sense now. We can't have const of something that is "pointer-like". The only thing that confuse me is the error messages. Basically, I can't have a const of pointer but only because there is no way to initialize it. – vonaka Aug 19 '19 at 12:55
  • 1
    Possible duplicates: [Why can't we declare a map and fill it after in the const?](https://stackoverflow.com/questions/42529691/why-cant-we-declare-a-map-and-fill-it-after-in-the-const/42529986#42529986); [Declare a constant array](https://stackoverflow.com/questions/13137463/declare-a-constant-array/29365828#29365828) – icza Aug 19 '19 at 17:16

1 Answers1

11

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

jano
  • 735
  • 7
  • 20