Golang program that uses structs as map keys


Golang is a powerful programming language that provides a variety of features to work with structured data. One of these features is the ability to use structs as keys in maps. In this article, we will explore how to write a Golang program that uses structs as map keys.

What is a Struct?

In Golang, a struct is a composite data type that groups together zero or more values of various types. Structs are used to create more complex data types that can represent a range of objects.

A struct is defined using the type and struct keywords, followed by a set of fields enclosed in braces. Here is an example of a struct definition in Golang −

type Person struct {
   Name string
   Age int
}

In this example, we have defined a struct named Person with two fields: Name and Age. The Name field is of type string and the Age field is of type integer.

Using Structs as Map Keys

In Golang, maps are used to associate values with keys. A map is defined using the map keyword, followed by the type of the key and the type of the value enclosed in brackets. Here is an example of a map definition in Golang −

var myMap map[string]int

In this example, we have defined a map named myMap with string keys and integer values.

To use a struct as a key in a map, we need to ensure that the struct is comparable. A struct is comparable if all its fields are comparable. This means that the fields must be of a primitive type, a struct type with comparable fields, or a pointer to a comparable type.

Example

Here is an example of a Golang program that uses a struct as a key in a map −

package main

import "fmt"

type Person struct {
   Name string
   Age int
}

func main() {
   personMap := make(map[Person]int)

   john := Person{"John", 25}
   jane := Person{"Jane", 30}

   personMap[john] = 100
   personMap[jane] = 200

   fmt.Println(personMap)
}

Output

map[{Jane 30}:200 {John 25}:100]

In this example, we have defined a struct named Person with two fields: Name and Age. We then define a map named personMap with Person keys and integer values.

We create two instances of the Person struct, john and jane, and set their respective Name and Age fields. We then use the make() function to create an empty personMap map and assign values to it by using john and jane as keys and 100 and 200 as values.

Finally, we print out the contents of the personMap map to the console.

Conclusion

Using structs as map keys is a powerful feature of the Golang programming language. By using structs as keys, you can create more complex data structures that allow you to store and retrieve values efficiently. By ensuring that your structs are comparable, you can take full advantage of the flexibility and power of Golang maps.

Updated on: 18-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements