登录
首页 >  Golang >  Go问答

无法进行编组,因为 go-redis Sdd 具有多个对象,并且没有实现 encoding.BinaryMarshaler 接口

来源:stackoverflow

时间:2024-03-22 22:30:31 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学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>