douxie7738 2017-04-09 12:24 采纳率: 0%
浏览 10
已采纳

保存和加载自定义类型

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
}
  • 写回答

1条回答 默认 最新

  • douchuanhan8384 2017-04-10 08:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要