A Golang map is an unordered collection of key-value pairs. The key can be of any type, including struct. You can create a golang map of the struct as keys.
You can create a map in golang using the below syntax:
map[KeyType]ValueType
A structure or struct in Golang is a user-defined type that contains fields of different types into a single type.
You can create struct
in golang using the below syntax:
type Employee struct{ name string Empid int }
In this article, we will discuss how to use struct as keys in the golang map.
How to Use Struct as Map Keys in Golang
To use struct as map keys in the golang program, create a structure and implement a structure as keys in a map.
package main import ( "fmt" ) // declare a struct type Employee struct { Empid int Name string Salary float64 } func main() { // Create struct instance e1 := Employee{Empid: 1, Name: "Alex", Salary: 2500} e2 := Employee{Empid: 2, Name: "Gary", Salary: 2850} e3 := Employee{Empid: 3, Name: "Dave", Salary: 4500} // Intialize map with struct as keys var emp_map = map[Employee]int{e1: 1, e2: 2, e3: 3} fmt.Println(emp_map)
The output of the above golang structure as keys in the map is:
map[{1 Alex 2500}:1 {2 Gary 2850}:2 {3 Dave 4500}:3]
To build a golang map of the struct, follow the below steps:
- Create a structure e.g.
Employee
- Create struct instance
- Create and initialize the map with struct as keys e.g.
map[Employee]int{e1:1,e2:2}
- In the map, a struct is used as a key type, and structure instances are used as a Value type.
- Print the map
Cool Tip: How to find map length in Golang!
Conclusion
I hope the above article to create a golang map of the struct as keys are helpful to you.
You can find more topics about the Golang tutorials on the GolangSpot Home page.