listgoredistype-conversiongo-redis

Why can't convert string to int with value got by go-redis?


I'm using go-redis in go to get list data from Redis.

IDs, err := redisClient.LRange("ID", 0, -1).Result()
if err != nil {
    panic(err)
}
fmt.Println(IDs)

for _, ID := range IDs {
    id, _ := strconv.Atoi(ID)
    fmt.Println(id)
}

In the first print, it can get right data:

37907

61357

45622

69007

But the second print got all 0:

0

0

0

0

If don't convert to int, it's string:

cannot use ID (type string) as type int in argument

So I want to use it as an integer.


I tested with a pure list in go:

var a [4]string
a[0] = "1"
a[1] = "2"
a[2] = "3"
a[3] = "4"
for _, i := range a {
    id, _ := strconv.Atoi(i)
    fmt.Println(id)
}

It can work without separate with new line:

1
2
3
4

So the go-redis's .LRange("ID", 0, -1).Result() returns not only string. https://godoc.org/github.com/go-redis/redis#Client.LRange It's *StringSliceCmd. How to conver it then?


Solution

  • It was because of wrong type.

    .LRange("ID", 0, -1).Result() returns []string. It should be converted to ids := strings.Fields(strings.Join(IDs, "")) then loop ids.