Golang program that uses structs as map keys

A map in Golang 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.

Syntax:

map[Key_Type]Value_Type{}

Example: var sample map[string]int

Here the sample is a map that has a string as key and int type as the value.

In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys. These structs should be compared with each other. A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type.



Example of a struct:

type Student struct {
      name string 
      rollno int
      class string
      city string
}

Let’s see how to implement a struct in a map:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show how to
// use structs as map keys
package main
  
// importing required packages
import "fmt"
  
//declaring a struct
type Address struct {
    Name    string
    city    string
    Pincode int
}
  
func main() {
  
    // Creating struct instances
    a2 := Address{Name: "Ram", city: "Delhi", Pincode: 2400}
    a1 := Address{"Pam", "Dehradun", 2200}
    a3 := Address{Name: "Sam", city: "Lucknow", Pincode: 1070}
  
    // Declaring a map
    var mp map[Address]int
      
    // Checking if the map is empty or not
    if mp == nil {
        fmt.Println("True")
    } else {
        fmt.Println("False")
    }
    // Declaring and initialising
    // using map literals
    sample := map[Address]int{a1: 1, a2: 2, a3: 3}
    fmt.Println(sample)
}
chevron_right

Output:

True
map[{Pam Dehradun 2200}:1 {Ram Delhi 2400}:2 {Sam Lucknow 1070}:3]

Iterating over a map: You can also run a loop to access and operate each map key individually.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show how to
// use structs as map keys
package main
  
// importing required packages
import "fmt"
  
// declaring a struct
type Address struct {
    Name    string
    city    string
    Pincode int
}
  
func main() {
    // Creating struct instances
    a1 := Address{"Pam", "Mumbai", 2200}
    a2 := Address{Name: "Ram", city: "Delhi", Pincode: 2400}
    a3 := Address{Name: "Sam", city: "Lucknow", Pincode: 1070}
  
    // Declaring and initialising using map literals
    sample := map[Address]int{a1: 1, a2: 2, a3: 3}
    for str, val := range sample {
        fmt.Println(str, val)
    }
  
    // You can also access a struct
    // field while using a loop
    for str := range sample {
        fmt.Println(str.Name)
    }
}
chevron_right

Output:

{Ram Delhi 2400} 2
{Sam Lucknow 1070} 3
{Pam Mumbai 2200} 1
Pam
Ram
Sam

Adding key: value pairs in the map: Adding key:value pair in a map is done using the given syntax:



map_name[struct_instance]=value 

If a key-value pair already exists in the map it will just update the old pair with the new.

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Adding key:value pair in a map
package main
  
// importing required packages
import "fmt"
  
// declaring a struct
type Student struct {
    Name   string
    rollno int
    course string
}
  
func main() {
  
    // Creating struct instances
    a1 := Student{"Asha", 1, "CSE"}
    a2 := Student{"Aishwarya", 1, "ECE"}
    a3 := Student{"Priya", 2, "MECH"}
  
    // Declaring and initialising
    // using map literals
    mp := map[Student]int{a1: 1, a2: 2}
    fmt.Println("Original map was", mp)
    mp[a3] = 3
    mp[Student{"Ram", 3, "CSE"}] = 4
  
    // Values have their zero values
    // Here initial value was 0 after 
    // incrementing it became 1
    mp[Student{"Tina", 44, "EEE"}]++
  
    fmt.Println("After adding key:value "+
     "pairs to the map, Updated map is:", mp)
}
chevron_right

Output:

Original map was map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1]
After adding key:value pairs to the map, Updated map is: map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1 {Priya 2 MECH}:3 {Ram 3 CSE}:4 {Tina 44 EEE}:1]

Deleting a struct key from the map: You can delete a struct key from the map using the delete() function. It is an inbuilt function and does not return any value and does not do anything if the key does not present in the given map. The syntax for the same is as follows:

delete(map_name, struct_key)

Example 4:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Deleting key: value pair in a map
package main
  
// importing required packages
import "fmt"
  
// declaring a struct
type Student struct {
    Name   string
    rollno int
    course string
}
  
func main() {
    // Creating struct instances
    a1 := Student{"Asha", 1, "CSE"}
    a2 := Student{"Aishwarya", 1, "ECE"}
    a3 := Student{"Priya", 2, "MECH"}
    a4 := Student{"Ram", 3, "CSE"}
  
    // Declaring and initialising using map literals
    mp := map[Student]int{a1: 1, a2: 2, a3: 3, a4: 4}
  
    delete(mp, a4)
    fmt.Println("The remaining map after deletion:")
    for str, i := range mp {
        fmt.Println(str, "=", i)
    }
  
}
chevron_right

Output:

The remaining map after deletion:
{Asha 1 CSE} = 1
{Aishwarya 1 ECE} = 2
{Priya 2 MECH} = 3

Checking the existence of a key: value pair: You can check whether a struct is present in the map or not. Given below is the syntax to check the existence of a struct_key: value pair in the map:

// This gives the value and check result
// If the check result is True, it means the key is present
// If the check result is False, it means the key is missing and in that case value takes a zero value
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]

Example 6:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to check if a
// struct key is present
package main
  
// importing required packages
import "fmt"
  
// declaring a struct
type Student struct {
    Name   string
    rollno int
    course string
}
  
func main() {
    // Creating struct instances
    a1 := Student{"Asha", 1, "CSE"}
    a2 := Student{"Aishwarya", 1, "ECE"}
    a3 := Student{"Priya", 2, "MECH"}
    a4 := Student{"Ram", 3, "CSE"}
  
    // Declaring and initialising
    // using map literals
    mp := map[Student]string{a1: "First"
     a2: "Second", a3: "Third", a4: "Fourth"}
  
    value, check := mp[a4]
    fmt.Println("Is the key present:", check)
    fmt.Println("Value of the key:", value)
  
    _, check2 := mp[a2]
    fmt.Println("Is the key present:", check2)
  
}
chevron_right

Output:

Is the key present: true
Value of the key: Fourth
Is the key present: true




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 :