create a struct with a field of type map in go

To create a struct with a field of type map in Go, you can define the struct with a field containing a map value, like this:

main.go
type Person struct {
    Name    string
    Address map[string]string
}
72 chars
5 lines

In the above example, the Person struct has a field called Address which is of type map[string]string. The keys of the map are string types, and the values of the map are also string types.

To use the Person struct, you can create a new instance of the struct, and assign values to its fields like this:

main.go
p := Person{
    Name: "John Doe",
    Address: map[string]string{
        "Street": "123 Main St",
        "City":   "Anytown",
        "State":  "CA",
        "Zip":    "12345",
    },
}
189 chars
10 lines

In the above example, we create a new instance of the Person struct, and assign values to its fields including the Address map field. The keys and values in the Address map field are populated during struct initialization using a map literal.

related categories

gistlibby LogSnag