我正在使用GO并尝试在redis中保存和检索struct的数组.我该如何实施呢? 我有以下结构 type Resource struct { title string} 并使用以下代码保存资源 _, err := redigo.Do("lpush", unique id, resource object);
我有以下结构
type Resource struct {
title string
}
并使用以下代码保存资源
_, err := redigo.Do("lpush", <unique id>, <resource object>);
现在我如何从redis中检索结构对象数组.
由于您要来回传递代码,我建议使用@Not_a_Golfer的解决方案.以下是您可以执行的操作示例:
package main
import (
"encoding/json"
"fmt"
)
type Emotions struct {
Sad bool
Happy Happy
Confused int
}
type Happy struct {
Money int
Moral bool
Health bool
}
func main() {
emo := &Emotions{Sad: true}
// retain readability with json
serialized, err := json.Marshal(emo)
if err == nil {
fmt.Println("serialized data: ", string(serialized))
//serialized data: {"Sad":true,"Happy":{"Money":0,"Moral":false,"Health":false},"Confused":0}
//do redis transactions...
}
//retriving whatever value stored in your redis instance...
var deserialized Emotions
err = json.Unmarshal(serialized, &deserialized)
if err == nil {
fmt.Println("deserialized data: ", deserialized.Sad)
//deserialized data: true
}
}
现在关于如何在redis上存储内容,这在很大程度上取决于您的数据.
