Golang Maps

In Go language, a map is a powerful, ingenious, and a versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys.

  • It is a reference to a hash table.
  • Due to its reference type it is inexpensive to pass, for example, for a 64-bit machine it takes 8 bytes and for a 32-bit machine, it takes 4 bytes.
  • In the maps, a key must be unique and always in the type which is comparable using == operator or the type which support != operator. So, most of the built-in type can be used as a key like an int, float64, rune, string, comparable array and structure, pointer, etc. The data types like slice and noncomparable arrays and structs or the custom data types which are not comparable don’t use as a map key.
  • In maps, the values are not unique like keys and can be of any type like int, float64, rune, string, pointer, reference type, map type, etc.
  • The type of keys and type of values must be of the same type, different types of keys and values in the same maps are not allowed. But the type of key and the type values can differ.
  • The map is also known as a hash map, hash table, unordered map, dictionary, or associative array.
  • In maps, you can only add value when the map is initialized if you try to add value in the uninitialized map, then the compiler will throw an error.

How to creating and initializing Maps?

In Go language, maps can create and initialize using two different ways:

  1. Simple: In this method, you can create and initialize a map without the use of make() function:

    Creating Map: You can simply create a map using the given syntax:



    // An Empty map
    map[Key_Type]Value_Type{}
    
    // Map with key-value pair
    map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}
    

    Example:

    var mymap map[int]string

    In maps, the zero value of the map is nil and a nil map doesn’t contain any key. If you try to add a key-value pair in the nil map, then the compiler will throw runtime error.
    Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to
    // create and initialize maps
    package main
      
    import "fmt"
      
    func main() {
      
        // Creating and initializing empty map
        // Using var keyword
        var map_1 map[int]int
      
        // Checking if the map is nil or not
        if map_1 == nil {
          
            fmt.Println("True")
        } else {
          
            fmt.Println("False")
        }
      
        // Creating and initializing a map
        // Using shorthand declaration and
        // using map literals
        map_2 := map[int]string{
          
                90: "Dog",
                91: "Cat",
                92: "Cow",
                93: "Bird",
                94: "Rabbit",
        }
          
        fmt.Println("Map-2: ", map_2)
    }

    chevron_right

    
    

    Output:

    True
    Map-2:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    
  2. Using make function: You can also create a map using make() function. This function is an inbuilt function and in this method, you just need to pass the type of the map and it will return an initialized map.]

    Syntax:

    make(map[Key_Type]Value_Type, initial_Capacity)
    make(map[Key_Type]Value_Type)
    

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to
    // create and initialize a map
    // Using make() function
    package main
      
    import "fmt"
      
    func main() {
      
        // Creating a map
        // Using make() function
        var My_map = make(map[float64]string)
        fmt.Println(My_map)
      
        // As we already know that make() function
        // always returns a map which is initialized
        // So, we can add values in it
        My_map[1.3] = "Rohit"
        My_map[1.5] = "Sumit"
        fmt.Println(My_map)
    }

    chevron_right

    
    

    Output:

    map[]
    map[1.3:Rohit 1.5:Sumit]
    

Important Points

  1. How to iterate over a map?: You can iterate a map using the range for loop. The value of this loop may vary because the map is an unordered collection.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how
    // to iterate the map using for
    // rang loop
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
      
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
      
        // Iterating map using for rang loop
        for id, pet := range m_a_p {
      
            fmt.Println(id, pet)
        }
    }

    chevron_right

    
    

    Output:

    90 Dog
    91 Cat
    92 Cow
    93 Bird
    94 Rabbit
    
  2. How to add key-value pairs in the map?: In maps, you are allowed to add key-value pairs in the initialized map using the given syntax:
    map_name[key]=value

    In maps, if you try to add an already existing key, then it will simply override or update the value of that key with the new value.


    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to add
    // a key-value pair in the map using
    // make() function
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
      
        fmt.Println("Original map: ", m_a_p)
      
        // Adding new key-value pairs in the map
        m_a_p[95] = "Parrot"
        m_a_p[96] = "Crow"
        fmt.Println("Map after adding new key-value pair:\n", m_a_p)
      
        // Updating values of the map
        m_a_p[91] = "PIG"
        m_a_p[93] = "DONKEY"
        fmt.Println("\nMap after updating values of the map:\n", m_a_p)
    }

    chevron_right

    
    

    Output:

    Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    Map after adding new key-value pair:
     map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 95:Parrot 96:Crow]
    
    Map after updating values of the map:
     map[90:Dog 91:PIG 92:Cow 93:DONKEY 94:Rabbit 95:Parrot 96:Crow]
    
  3. How to retrieve a value related to a key in the maps?: In maps, you can retrieve a value with the help of key using the following syntax:
    map_name[key]

    If the key doesn’t exist in the given map, then it will return zero value of the map, i.e, nil. And if the key exists in the given map, then it will return the value related to that key.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to
    // retrieve the value of the key
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
        fmt.Println("Original map: ", m_a_p)
      
        // Retrieving values with the help of keys
        value_1 := m_a_p[90]
        value_2 := m_a_p[93]
        fmt.Println("Value of key[90]: ", value_1)
        fmt.Println("Value of key[93]: ", value_2)
    }

    chevron_right

    
    

    Output:

    Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    Value of key[90]:  Dog
    Value of key[93]:  Bird
    
  4. How to check the existence of the key in the map?: In maps, you can check whether the given key exists or not using the following syntax:
    // With value
    // It will gives the value and check result
    value, check_variable_name:= map_name[key]
    
    or
    
    // Without value using the blank identifier
    // It will only give check result
    _, check_variable_name:= map_name[key]
    

    Here, if the value of the check_variable_name is true which means the key exists in the given map and if the value of check_variable_name is false which means the key does not exist in the given map.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to
    // check the key is available or not
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
      
        fmt.Println("Original map: ", m_a_p)
      
        // Checking the key is available
        // or not in the m_a_p map
        pet_name, ok := m_a_p[90]
        fmt.Println("\nKey present or not:", ok)
        fmt.Println("Value:", pet_name)
      
        // Using blank identifier
        _, ok1 := m_a_p[92]
        fmt.Println("\nKey present or not:", ok1)
    }

    chevron_right

    
    

    Output:

    Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    
    Key present or not: true
    Value: Dog
    
    Key present or not: true
    
  5. How to delete key from the map?: In maps, you are allowed to delete the key present in the map using the delete() function. It is inbuilt function and does not return any value and does not do anything if the key does not present in the given map. In this function, you just simply pass the map and key which you want to delete from the map.

    Syntax:

    delete(map_name, key)

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate how to delete a key
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
      
        fmt.Println("Original map: ", m_a_p)
      
        // Deleting keys
        // Using delete function
        delete(m_a_p, 90)
        delete(m_a_p, 93)
      
        fmt.Println("Map after deletion: ", m_a_p)
    }

    chevron_right

    
    

    Output:

    Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    Map after deletion:  map[91:Cat 92:Cow 94:Rabbit]
    
  6. Modifiying map: As we know that maps are of reference type. So, when we assign an existing map to a new variable, both the maps still refer to the same underlying data structure. So, when we update one map it will reflect in another map.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Go program to illustrate the
    // modification concept in map
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a map
        m_a_p := map[int]string{
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
        }
        fmt.Println("Original map: ", m_a_p)
      
        // Assigned the map into a new variable
        new_map := m_a_p
      
        // Perform modification in new_map
        new_map[96] = "Parrot"
        new_map[98] = "Pig"
      
        // Display after modification
        fmt.Println("New map: ", new_map)
        fmt.Println("\nModification done in old map:\n", m_a_p)
    }

    chevron_right

    
    

    Output:

    Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
    New map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]
    
    Modification done in old map:
     map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]
    


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.