59

Why can't I create constant struct?

const FEED_TO_INSERT = quzx.RssFeed{ 0,
                    "",
                    "desc",
                    "www.some-site.com",
                    "upd_url",
                    "img_title",
                    "img_url",
                    0,
                    0,
                    0,
                    0,
                    0,
                    100,
                    "alt_name",
                    1,
                    1,
                    1,
                    "test",
                    100,
                    100,
                    0 }

.\rss_test.go:32: const initializer quzx.RssFeed literal is not a constant

mklement0
  • 312,089
  • 56
  • 508
  • 622
ceth
  • 42,340
  • 57
  • 170
  • 277
  • 1
    Can you add the link to the answered question? It would be good to link back to the original question for duplicating. – Zhenhua Nov 14 '17 at 23:30
  • 2
    Flagging to reopen. Asking if you can make a constant struct is different to asking about an array, even if the *answers* are similar. – Duncan Jones May 02 '19 at 11:15

3 Answers3

86

Because Go does not support struct constants (emphasis mine)

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

Read more here: https://golang.org/ref/spec#Constants

mkopriva
  • 28,154
  • 3
  • 45
  • 61
25

A good workaround is to wrap it in a function.

func FEED_TO_INSERT() quzx.RssFeed {
    return quzx.RssFeed{ 0,
                    "",
                    "desc",
                    "www.some-site.com",
                    "upd_url",
                    "img_title",
                    "img_url",
                    0,
                    0,
                    0,
                    0,
                    0,
                    100,
                    "alt_name",
                    1,
                    1,
                    1,
                    "test",
                    100,
                    100,
                    0 }
}

Note: Make sure that the function is always returning a new object(or copy).

Ihor
  • 423
  • 4
  • 8
15

You should declare it as a var.

Go allows you to declare and initialize global variables at module scope.

Go does not have any concept of immutability. 'const' is not meant as a way to prevent variables from mutating or anything like that.

user10753492
  • 630
  • 4
  • 8
  • 1
    This is true (`const` in Go is closer to `#define` in C than to `readonly` in C#), but doesn't really explain why there can't be struct-like `const` values. They were probably excluded (along with array-like and map-like values) to simplify the compiler design. – kbolino Sep 19 '21 at 18:38