create a map with a value of type struct in go

To create a map with a value of type struct in Go, first you need to define the struct type. Let's define a simple struct type called Person:

main.go
type Person struct {
    Name string
    Age  int
}
52 chars
5 lines

Now, to create a map with a value of type Person, you can do the following:

main.go
people := map[string]Person{
    "Alice": Person{Name: "Alice", Age: 25},
    "Bob":   Person{Name: "Bob", Age: 30},
}
119 chars
5 lines

Here, we are creating a map with string keys and Person values. We are initializing the map with two Person values, one for the key "Alice" and one for the key "Bob".

You can also add values to the map later using the same syntax:

main.go
people["Charlie"] = Person{Name: "Charlie", Age: 35}
53 chars
2 lines

Now, the map will have three keys ("Alice", "Bob", and "Charlie") with corresponding Person values.

related categories

gistlibby LogSnag