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(IDs)
}

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?

id, _ := strconv.Atoi(i)

The second _ in that statement is the error value it returns. You should change this line to id, err := strconv.Atoi(i) and handle that error.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.