Jump to content

Constant Maps in Golang (Constant Map)


Linux Hint

Recommended Posts

When it comes to versatile and powerful data structures, maps are at the forefront of the list. Maps, also known as associative arrays, dictionaries, or hash maps, allow us to store and retrieve the key-value pairs in an efficient and memory safe method.

By default, maps are mutable and hence can be modified across the lifetime of the application. However, you may come across instances where you need to define a constant or immutable map.

An immutable map is an essential map that can be modified once declared to ensure the data integrity and store the non-changing information.

In this tutorial, we will go over the fundamentals of working with maps, understanding what constant maps are, and why we need it.

Golang Maps

Before we dive into the process of defining a constant map, let us start with the fundamentals of maps in Go.

Declaration

In Go, we can declare a map using the “map” keyword followed by the key and value types that are enclosed in square brackets.

The syntax is as follows:

var m map[KeyType]ValueType

 
An example is as follows:

var m map[string]int

 
Initialization

Before we can use a map, we need to initialize a map. In Go, we can do this using the “make” function as follows:

m := make(map[string]int)

 
Adding and Accessing the Elements

Once we initialize a map, we can add the elements to a map by assigning a value to a specific key.

An example is as follows:

m["MySQL"] = 3306
m["PostgreSQL"] = 5094

 
To access the value that is associated with a key, use the key within the square brackets as shown in the following example:

fmt.Println(m["PostgreSQL"])

 
This should return the value that is associated with the specified key.

Golang Constant Map

As we mentioned, a constant map, also known as an immutable map, is a Go map that cannot be modified after initialization.

In an immutable map, once we define it, we cannot add, update, or delete any key-value pairs.

Some common characteristics of an immutable map in Go include the following:

    • The key-value pairs are defined at compile time.
    • We cannot declare a constant map using the “const” keyword.
    • A constant map is evaluated and populated during compilation and not at runtime.

Some common instances where you might need to use a constant map include the following:

    1. When you need to store an immutable configuration that does not change during the program execution.
    2. Lookup tables – If you have a fixed data that you need to look up in an efficient manner, an immutable map can help for improved performance.

Create a Constant Map in Golang

In Go, we cannot define a map as constant using the “const” keyword. This is because maps are reference types and hence their contents are mutable.

To declare a constant map in Go, we can use an anonymous function to create a constant map-like object.

An example is as follows:

package main
import "fmt"
func main() {
    readOnlyMap := GetReadOnlyMap()

    value, ok := readOnlyMap["MySQL"]
    if ok {
        fmt.Printf("Value of key1: %d\n", value)
    } else {
        fmt.Println("Key not found")
    }
}
func GetReadOnlyMap() map[string]int {
    readOnly := map[string]int{
        "MySQL":   3306,
        "MongoDB": 27071,
        "Redis":   6379,
    }
    return readOnly
}

 
In this example, the “GetReadOnlyMap” function returns a map with immutable data. Since it is an anonymous function call, the map is effectively immutable which prevents modifications.

We can, however, read the values of the map from the readOnlyMap without the functionality of writing to the map.

Conclusion

In this tutorial, we learned all about maps in Go. We learned how they work (reference), what constant maps are, and how to use an anonymous function to declare one.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...