In this article, we will see how to create a custom type which is a map of structs in Go by using the inbuilt types such as struct and map types.
Define the struct
Design the struct named Employee that contains three members i.e. Name, Age, and Email as shown below.
type Employee struct {
Name string
Age int
Email string
}
Create and initialize the map
Next, initialize the map using the make
function, specifying the key and value types. In the below example, the key type can be any hashable type, such as string or int, and the value type is the struct which we have defined above.
The below map uses the employee ID as a key which is of type int and the employee data as an Employee type
people := make(map[int]Employee)
Add data to map
Add the data to the map as shown below. Simply assign a new struct instance to a specific key in the map to add the data to map.
people[1001] = Employee{Name: "John Doe", Age: 25, Email: "john@example.com"}
people[1002] = Employee{Name: "Jane Smith", Age: 30, Email: "jane@example.com"}
Accessing the data from Map of struct
You can access the individual employee data using the map key i.e. the employee ID. You can also iterate over the structure as shown below.
john := people["john"]
john.Age = 26
people["john"] = john
/* Iterate over the struct */
for key, value := range people {
fmt.Println(key, value)
}
Here is the complete example:
package main
import "fmt"
type Person struct {
Name string
Age int
Email string
}
func main() {
people := make(map[string]Person)
people["john"] = Person{Name: "John Doe", Age: 25, Email: "john@example.com"}
people["jane"] = Person{Name: "Jane Smith", Age: 30, Email: "jane@example.com"}
john := people["john"]
john.Age = 26
people["john"] = john
for key, value := range people {
fmt.Println("Key:", key)
fmt.Println("Value:", value)
fmt.Println("------")
}
}