简体   繁体   中英

Can't marshal, (implement encoding.BinaryMarshaler). go-redis Sdd with multiple objects

I have a following piece of code in which I am trying to add an array to a redis set but it is giving me an error.

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)
}


I get the error can't marshal [2]main.Info (implement encoding.BinaryMarshaler)

I have also tried to convert each info to []byte and pass in the [][]byte... to SAdd but same error. How would I do this idomatically?

MarshalBinary() method should be as below

func (i Info) MarshalBinary() ([]byte, error) {
    return json.Marshal(i)
}

note: Info instead of *Info

Redis is based on key-value pairs, and key-values are all strings and other string-based data structures. Therefore, if you want to put some data into redis, you should make these data strings.

I think you should implement this interface like code below to make go-redis able to stringify your type:

func (i Info) MarshalBinary() (data []byte, err error) {
    bytes, err := json.Marshal(i) \\edited - changed to i
    return bytes, err
}

In this way, you implement this method and go-redis will call this method to stringify(or marshal) your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM