拼合嵌套结构导致一片切片 [英] Flattening nested structs leads to a slice of slices
本文介绍了拼合嵌套结构导致一片切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类型总线结构{
数字字符串
名称字符串
DirectStations [] Station // Station是另一个结构
ReverseStations [] Station
}
,我试图将这个实例存储到数据存储中:
key:=数据存储。 NewKey(c,Bus,bus.Number,0,nil)
pre>
_,err:= datastore.Put(c,key,& bus)
但我收到错误
数据存储:$
字段DirectStations
b
$ b <如何解决这个问题?
编辑:
原来你可以'
解决方案只需将此结构编码为json(字节)并存储数据存储区中的json
编辑/更新
包主
导入(
encoding / json
fmt
)
类型总线结构{
数字字符串`json:数字``
名称字符串`json:name`
DirectStations [] Station`json:directstation`// Station是另一个结构
ReverseStations [] Station`json:reversestation`
}
类型站点结构{
StationName字符串`json:stationname`//这些标记名称必须完全匹配它们在json
}中的外观
func toJson(i interface {})[] byte {
data,err:= json.Marshal(i)
if err!= nil {
panic(err)$ b $ (v,vv)
返回数据
b
$ b func main(){
bus:= Bus {}
st:= [] Station {{station1},{station2 }}
bus.DirectStations = make([] Station,len(st))
for i,v:= range st {
bus.DirectStations [i] = v
}
bus.Number =2
bus.Name =BusName$ b $ j js:= toJson(bus)
fmt.Println(JSON OUTPUT,string(js))
bus2:= Bus {}
fromJson(js,& bus2)
fmt.Printf(ORIGINAL STRUCT OUTPUT%#v,bus2)
}
http://play.golang.org/p/neAGgcAIZG
So I have a struct like this
type Bus struct { Number string Name string DirectStations []Station // Station is another struct ReverseStations []Station }
and I'm trying to store an instance of this to the Datastore:
key := datastore.NewKey(c, "Bus", bus.Number, 0, nil) _, err := datastore.Put(c, key, &bus)
but I'm getting the error
datastore: flattening nested structs leads to a slice of slices: field "DirectStations"
How does one solve this?
Edit:
Turns out you can't have a slice of struct, where that struct contains other slices.
解决方案Just encode this struct into json (bytes) and store the json in the datastore
EDIT / UPDATE
package main import ( "encoding/json" "fmt" ) type Bus struct { Number string `json:"number"` Name string `json:"name"` DirectStations []Station `json:"directstation"` // Station is another struct ReverseStations []Station `json:"reversestation"` } type Station struct { StationName string `json:"stationname"` // these tag names must match exactly how they look in json } func toJson(i interface{}) []byte { data, err := json.Marshal(i) if err != nil { panic(err) } return data } func fromJson(v []byte, vv interface{}) { json.Unmarshal(v, vv) } func main() { bus := Bus{} st := []Station{{"station1"}, {"station2"}} bus.DirectStations = make([]Station, len(st)) for i, v := range st { bus.DirectStations[i] = v } bus.Number = "2" bus.Name = "BusName" js := toJson(bus) fmt.Println("JSON OUTPUT", string(js)) bus2 := Bus{} fromJson(js, &bus2) fmt.Printf("ORIGINAL STRUCT OUTPUT %#v", bus2) }
http://play.golang.org/p/neAGgcAIZG
这篇关于拼合嵌套结构导致一片切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文