【问题标题】:save and loading custom types保存和加载自定义类型
【发布时间】:2017-04-09 12:24:53
【问题描述】:

我有一个自定义类型 map[string]map[string]string 正在尝试保存在 Google 数据存储中,保存按预期工作。但是加载函数抱怨assignment to entry in nil map

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

上面的类型是map[string]string的映射,目的是保存不同的地址类型。

//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
}

在加载函数中,我引用了作为 map[string]string 映射的地址,它保存了以下示例 JSON 格式。

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

下面的保存功能运行良好,数据存储在数据存储中。然而,Load 是一个相当棘手的虫子。

//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
}

地址结构的工作负载

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

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

【问题讨论】:

    标签: google-app-engine go google-cloud-datastore


    【解决方案1】:

    首先,关于声明 - https://stackoverflow.com/a/42901715/4720042

    接下来,我觉得您应该为此使用自定义结构。 即使您仍想使用map[string]map[string]string,您也不能分配给地图中尚未明确定义的字段,即。 property.Name

    如果您打算稍后添加元素,则必须使用 make 初始化该地图。

    【讨论】:

    • 我尝试在加载函数中初始化结构,认为这也会初始化映射 a = &Address{} 但是虽然没有抛出错误,但输出为零。我需要将地址显示为 map[string]map[string]string 我看不出调整地址结构还有什么帮助。地址将用于其他模型公司、用户、商店等。如果我可以保存,我应该可以轻松加载。
    • 在调用 Load 之前,只需初始化您传递给它的任何变量,在这种情况下,a 为 := make(Address) 我试图在这里复制您的问题 - @ 987654322@
    • 我理解这种情况,但是在数据存储的实例中,我没有权限在数据存储调用加载或保存之前进行初始化。一切都发生在内部。
    • 在这种情况下,请在函数 Load 的第一行使用 *a = make(Address)。有可能吗?
    • 像魅力一样工作,我已经声明如下 a = &Address{},但是 *a = make(Address) 是赢家。感谢您的宝贵时间。
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 2016-08-15
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多