0

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?

iooi
  • 453
  • 2
  • 10
  • 23
  • 4
    Check the error returned from `strconv.Atoi`, it will usually contain info on why it failed to parse the string. Also your `fmt.Println` inside the loop is printing `IDs`, not `id`, that's a typo in the question I assume but if it isn't that might be your problem. And for debugging try printing the individual strings with `fmt.Printf("%q\n", ID)` this will show you also non-printable characters, like whitespace, that the string may contain and which may cause the conversion to fail. – mkopriva Jan 05 '21 at 08:55
  • There may be some extra char in the strings check error – Shubham Srivastava Jan 05 '21 at 10:08
  • My bad. It should be `fmt.Println(id)` inside loop. I printed convert error. 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`. – iooi Jan 05 '21 at 10:09
  • @iooi Please Post an answer and mark it as solved. This will help other users with the same problem to easier find the solution. – Emanuel Bennici Jan 05 '21 at 21:05

1 Answers1

0

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.

iooi
  • 453
  • 2
  • 10
  • 23