Constant struct in Go

Go

Go Problem Overview


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

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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

Solution 3 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncethView Question on Stackoverflow
Solution 1 - GomkoprivaView Answer on Stackoverflow
Solution 2 - GoIhorView Answer on Stackoverflow
Solution 3 - Gouser10753492View Answer on Stackoverflow