Declare golang constant maps - is it possible? [SOLVED]

Golang constant maps

As you might realized one of the core features of Go is simplicity, while still extremely fast, Go restricts developers to fall into some mistakes, and instead enforces certain rules, in order to keep Go code as clean as possible.

So in Go all variables must have a type, whether you the programmer telling Go, the type, or using type inference and the compiler decide. for certain types of course. Either way, is fine, but then there pointers pointing to the actual memory allocated, which gives more power, and efficiency you don't send the entire data, like an array or a struct, you instead only send the location, and Go can read and manipulate the data, efficiently.

Advertisement

Now there is constants, constants they should be created at compile time, they also should be either: strings, runes, booleans or numbers.

So if you need a constant map, read carefully:

 

Why Go doesn’t support constant maps?

Reason 1

So having constant maps (or structs or slices…) would need go to figure out the type, which can be accomplished by adding a read-only feature to the Go lang, by Adding some kind of const-qualifier to the language, however as you might have guessed its a long discussion and can only be in version 2 of Go.

 

Reason 2

If on the other hand we want something like type inference to get the type at compile time, then it makes it cumbersome for allowing copying or modifying the map then just discard them.

If you want to read further, please reference to

If you come here you are insisting on using my approach on constant maps, so let me show you how:

Advertisement

 

Tricks to declare Constant maps in GO

Method 1: function

We can create a function that takes a function as an argument and then use it as a closer, to return the value of the map, based on the index you provide

func GetContinents() func(int) string {
	theMap := map[int]string{
		70: "Asia",
		60: "Afria",
		50: "Europe",
		40: "North America",
		30: "South America",
		20: "Australia/Oceania",
		10: "Antractica",
	}

	return func(key int) string {
		return theMap[key]
	}
	return func(key int) string {
		return theMap[key]
	}
}

To test this, lets get values out of index, 10, 100, and then 400 like below

func main() {
	// prints the continent based on the key/idex
	fmt.Println(GetContinents()(10))
	fmt.Println(GetContinents()(20))

	continent := GetContinents()
	fmt.Println(continent(50))
}

This will print out

Antractica
Australia/Oceania
Europe

 

Method 2: variable function

If you want a slightly different version using a variable of a map, you can do so by:

var GetContinents = func() map[int]string {
	return map[int]string{
		70: "Asia",
		60: "Afria",
		50: "Europe",
		40: "North America",
		30: "South America",
		20: "Australia/Oceania",
		10: "Antractica",
	}
}

// prints the number based on the key/idex
func PrintContinent(key int) {
	fmt.Println(GetContinents()[key])
}

// prints the number, and N as many repeatitions as you want
func PrintContinentRepeat(key, n int) {
	fmt.Println(strings.Repeat(GetContinents()[key], n))
}

func main() {
	PrintContinent(10)
	PrintContinent(50)
	PrintContinentRepeat(10, 5)
}

This will print out values with index, 1000, 50, then 10 repeated 5 times.

Antractica
Europe
AntracticaAntracticaAntracticaAntracticaAntractica

 

Method 3: variable struct

Another examples if if you want to only use a variable struct

var GetContinents = struct {
    list map[int]string
}{list: map[int]string {
		70: "Asia",
		60: "Afria",
		50: "Europe",
		40: "North America",
		30: "South America",
		20: "Australia/Oceania",
		10: "Antractica",
}}

func main() {
		// prints the continent based on the key/idex
    d := 10
    fmt.Printf("Continent of Key (%d): %s", d, GetContinents.list[10])
}

This prints out

Value of Key (10): Antractica

 

Conclusion

At the cost of the language simplicity, and having the power of non-exported variables and ability for you to restrict there manipulation using functions returning values, would act just like a constant. Now we know that we can not declare constant maps directly in golang as other programming languages. In this tutorial we covered different workaround hacks to declare golang constant maps.

 

References

How to declare a constant map in Golang?

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X