Redis: can't marshal []interface {} (consider implementing encoding.BinaryMarshaler)

Created on 8 Mar 2018  路  8Comments  路  Source: go-redis/redis

redis.SAdd("words", "1213")
redis: can't marshal []interface {} (consider implementing encoding.BinaryMarshaler)

Most helpful comment

You can do two things, choose what works better for you:

  1. Implement encoding.BinaryMarshaler and encoding.BinaryUnMarshaler for your type and Redis will do it automatically all operations
  2. Manually marshal/unmarshal to []byte as json and store []byte in Redis

All 8 comments

Your code should be more like redis.SAdd("words", []interface{}{"1213", "12123"}).

I want do save one object into redis, but also have this problem.
code:

func SetUser(user UserBean) error {
key := fmt.Sprintf("user:%s", user.Name)
_, err := Client().Set(key, user, time.Hour).Result()
return err
}

You can do two things, choose what works better for you:

  1. Implement encoding.BinaryMarshaler and encoding.BinaryUnMarshaler for your type and Redis will do it automatically all operations
  2. Manually marshal/unmarshal to []byte as json and store []byte in Redis

encoding.BinaryMarshaler and encoding.BinaryUnMarshaler are interfaces methods that you would need to override in your particular struct.

type MyStruct struct{}

func(m *MyStruct)UnmarshalBinary(data []byte) error{
  // convert data to yours, let's assume its json data
  return json.Unmarshal(data, m)
}

The second case would be to store as []byte in Redis and manually do the same thing. Mind you I just typed by memory the code above, might have errors. Cheers.

Oh, I deleted my message to which you replied. I asked him for an example. Thank you a lot @mauleyzaola :)

i tried to use eval but still have the same error message after implement binary marshaller and unmarshaler. seems like the 1st solution is not working

that's worked

type MyStruct struct{}

func (m *MyStruct) MarshalBinary() ([]byte, error) {
    return json.Marshal(m)
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

pranas picture pranas  路  8Comments

chenweiyj picture chenweiyj  路  3Comments

mikhailsizov picture mikhailsizov  路  5Comments

mathvav picture mathvav  路  3Comments

zhangruiskyline picture zhangruiskyline  路  7Comments