Ahm*_*han 0 marshalling go go-redis
我有以下一段代码,我试图在其中将数组添加到 redis 集,但它给了我一个错误。
package main
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
)
type Info struct {
Name string
Age int
}
func (i *Info) MarshalBinary() ([]byte, error) {
return json.Marshal(i)
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
ReadTimeout: -1,
})
pong, err := client.Ping().Result()
fmt.Print(pong, err)
infos := [2]Info{
{
Name: "tom",
Age: 20,
},
{
Name: "john doe",
Age: 30,
},
}
pipe := client.Pipeline()
pipe.Del("testing_set")
// also tried this
// pipe.SAdd("testing_set", []interface{}{infos[0], infos[1]})
pipe.SAdd("testing_set", infos)
_, err = pipe.Exec()
fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)
我收到错误 can't marshal [2]main.Info (implement encoding.BinaryMarshaler)
我还尝试将每个信息转换为[]byte并传递[][]byte...到SAdd但相同的错误。我将如何以惯用方式做到这一点?
MarshalBinary() 方法应该如下
func (i Info) MarshalBinary() ([]byte, error) {
return json.Marshal(i)
}
Run Code Online (Sandbox Code Playgroud)
注意:信息而不是*信息
小智 5
Redis是基于键值对的,而键值都是字符串和其他基于字符串的数据结构。因此,如果你想将一些数据放入redis中,你应该制作这些数据字符串。
我认为你应该像下面的代码一样实现这个接口,以使 go-redis 能够字符串化你的类型:
func (i Info) MarshalBinary() (data []byte, err error) {
bytes, err := json.Marshal(i) \\edited - changed to i
return bytes, err
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您实现了此方法,go-redis 将调用此方法来字符串化(或编组)您的数据。
| 归档时间: |
|
| 查看次数: |
4268 次 |
| 最近记录: |