通过下面的示例代码,Redis(使用 go-redis )存储:
我想将嵌套的“Bite”结构存储在原始结构的哈希中。 目前,我从其他posts看到的唯一解决方案建议使用 Redis 的不同数据结构(例如 JSON、YAML 来保留整个结构和嵌套结构)或通过键创建与第一个结构相关的子哈希(即
insect:blackwidow:bite"
)。
package main
import (
"context"
"log"
)
type Bite struct {
Power string `redis:"power"`
Toxic bool `redis:"toxic"`
}
type Insect struct {
Name string `redis:"name"`
Description string `redis:"description"`
Bite Bite
Legs int `redis:"legs"`
}
func main() {
client, err := InitRedis()
if err != nil {
log.Panic(err)
}
ctx := context.Background()
spiderA := Insect{Name: "blackwidow", Description: "small but deadly", Bite: Bite{"deadly", true}, Legs: 8}
spiderB := Insect{Name: "daddylonglegs", Description: "long and thin. harmless", Bite: Bite{"can't bite", false}, Legs: 8}
insects := []Insect{spiderA, spiderB}
for _, i := range insects {
if err := client.HSet(ctx, "insect:"+i.Name, i).Err(); err != nil {
panic(err)
}
}
}
/*
> scan 0 MATCH *insect* COUNT 10
1) "0"
2) 1) "insect:blackwidow"
2) "insect:daddylonglegs"
*/
在我接近
unmarshal
之前,我用go-redis
解决了这个问题。
type Bite struct {
Power string `json:"power"`
Toxic bool `json:"toxic"`
}
type InsectJSON struct {
Name string `json:"name"`
Description string `json:"description"`
Bite Bite
Legs int `json:"legs"`
}
type Insect struct {
Name string `redis:"name"`
Description string `redis:"description"`
Power string `redis:"power"`
Toxic bool `redis:"toxic"`
Legs int `redis:"legs"`
}
func (i *Insect) UnmarshalJSON(data []byte) error {
var ij InsectJSON
if err := json.Unmarshal(data, &ij); err != nil {
return err
}
i.Name = ij.Name
i.Description = ij.Description
i.Power = ij.Bite.Power
i.Toxic = ij.Bite.Toxic
i.Legs = ij.Legs
return nil
}