无法进行编组,因为 go-redis Sdd 具有多个对象,并且没有实现 encoding.BinaryMarshaler 接口
时间:2024-03-22
浏览:321
作者:佚名
在使用 go-redis SADD 命令时,无法将数组添加到 Redis 集合中。这是因为 go-redis SADD 期望提供单个对象或实现 encoding.BinaryMarshaler 接口的多个对象,而数组不满足这些条件。
问题内容
我有下面一段代码,我试图将一个数组添加到 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)
}
我收到错误 can't marshal [2]main.info(实现编码.binarymarshaler)
我还尝试将每个信息转换为 []byte 并将 [][]byte... 传递给 sadd 但同样的错误。我将如何按照理想方式做到这一点?
解决方案
marshalbinary() 方法应如下所示
func (i Info) MarshalBinary() ([]byte, error) {
return json.Marshal(i)
}
注意:信息而不是*信息
以上就是《无法进行编组,因为 go-redis Sdd 具有多个对象,并且没有实现 encoding.BinaryMarshaler 接口》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
