isawk
isawk

Reputation: 1057

save and loading custom types

I have a custom type map[string]map[string]string am trying to save in Google Datastore, the save works as expected. However the load functions complains about assignment to entry in nil map

//Address represents address
type Address map[string]map[string]string

Type above is a map of map[string]string, target at saving different address types.

//Load function from PropertyLoaderInterface helps datastore load this object
func (a *Address) Load(dp []datastore.Property) error {
    for _, property := range dp {
        (*a)[property.Name] = util.InterfaceToMapString(property.Value)
    }
    return nil
}

In the load function I deference the Address which is a map of map[string]string, it saves the following example JSON format.

"Company":{
    "physicalAddress": "",
    "postalAddress": "",
    "physicalCity": "",
    "postalCity": "",
    "physicalCode": "",
    "postalCode": "",
    "physicalCountry": "",
    "postalCountry": ""
}

Save function below works well and data is store in datastore. The Load is however rather a tricky bugger.

//Save function from PropertyLoaderInterface helps datastore save this object
func (a *Address) Save() ([]datastore.Property, error) {
    propertise := []datastore.Property{}
    for name, value := range *a {
        propertise = append(propertise, datastore.Property{Name: name,
            NoIndex: true,
            Value:   util.MapToJSONString(value)})
    }

    return propertise, nil
}

Working load for Address struct

func (a *Address) Load(dp []datastore.Property) error {
    *a = make(Address)

    for _, property := range dp {
        (*a)[property.Name] = util.InterfaceToMapString(property.Value)
    }
    return nil
}

Upvotes: 1

Views: 166

Answers (1)

Gaurav Ojha
Gaurav Ojha

Reputation: 1177

First, regarding the declarations - https://stackoverflow.com/a/42901715/4720042

Next, I feel you should instead use a custom struct for this purpose. Even if you still want to use a map[string]map[string]string, you cannot assign to a field in a map that hasn't been explicitly defined viz. property.Name

You have to initialize that map with make if you plan on adding the elements later.

Upvotes: 2

Related Questions