Search code examples
goredisredigo

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


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?


Solution

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