0

I'm getting data from the redis.HGetAll but found no clean way to convert results into my Struct.

var object struct {
    x int
}

result := redisClient.HGetAll(context.Background(), "the_h_key")

//TODO import the result content into the object 

Is there any function for this spectacular case?

I'm using the JSON package(marshal, then UnMarshal to a struct).

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46

2 Answers2

2

The result from Redis is a map[string]string. For each field in the struct, get the value from the map, convert the string to the field type and assign to the field.

 var o object
 var err error

 o.x, err = strconv.Atoi(m["x"])
 if err != nil {
      // handle the error
 }

 ... repeat for other fields as needed
Taylor Rex
  • 21
  • 1
1

If your datastructure isn't too complex, one convenient way to save data using redis is as jsons. Just json.Marhsal() your struct and save it as a string and then json.Unmarshal() that string into your struct back.

Vaibhav Mishra
  • 415
  • 3
  • 10
  • I'm using this way for now. But this way has lot of encode/decode, and Redis hash ability is useless here. – Amin Shojaei Aug 01 '20 at 18:56
  • You can build a wrapper function to avoid code repetition @AminShojaei – Vaibhav Mishra Aug 01 '20 at 18:58
  • You are right about code itself. but the real problem is about performance. It will be better if we avoid json encode/decode, and use the pure data instead. – Amin Shojaei Aug 01 '20 at 19:34
  • 2
    I understand. I don't think `go-redis` supports that. I've noticed another package `redigo` having a `Scan` method but haven't personally used it though. – Vaibhav Mishra Aug 01 '20 at 20:49
  • 1
    Chipping in quite later but will make an attempt to clarify things: `Scan` is a different command, it's not like the `row.Scan` from the `sql` package that scans the value and adds it to a pointer. Also, the initial quest of the OP is to avoid marshalling/unmarshalling a value (essentially a strict), since they're concerned hash functionality of redis is entirely unused that way. – Kostas Livieratos Oct 20 '21 at 11:51