Error - redigo.Scan: Cannot convert from Redis bulk string to *string

1.3k Views Asked by At

I have a struct like that

type User struct {
    Nickname  *string `json:"nickname"`
    Phone     *string `json:"phone"`
}

Values ​​are placed in redis with HMSET command. (values ​​can be nil)

Now I'm trying to scan values ​​into a structure:

values, err := redis.Values(Cache.Do("HMGET", "key", "nickname", "phone" )

var usr User

_, err := redis.Scan(values, &usr.Nickname, &usr.Phone)

But I get an error

redigo.Scan: cannot assign to dest 0: cannot convert from Redis bulk string to *string

Please tell me what I'm doing wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

The Scan documentation says:

The values pointed at by dest must be an integer, float, boolean, string, []byte, interface{} or slices of these types.

The application passes a pointer to a *string to the function. A *string is not one of the supported types.

There are two approaches for fixing the problem. The first is to allocate string values and pass pointers to the allocated string values to Scan:

usr := User{Nickname: new(string), Phone: new(string)}
_, err := redis.Scan(values, usr.Nickname, usr.Phone)

The second approach is to change the type of the struct fields to string:

type User struct {
    Nickname  string `json:"nickname"`
    Phone     string `json:"phone"`
}

...

var usr User
_, err := redis.Scan(values, &usr.Nickname, &usr.Phone)
1
On

From the doc it says that []byte is type for bulk string, not *string. You have two options here:

  1. change the particular field type to []byte
  2. or use temporary variable with []byte type on the scan, then after the data retrieved store it to the struct's field