2

I am trying to rpush multiple elements to a redis key. Currently using a redis pool connection using https://github.com/gomodule/redigo.

If I try to put an array into rpush , a string with the array concatenated is pushed. How can I push individual elements instead

conn := Pool.Get() // A redigo redis pool 
arr := []string{"a", "b", "c", "d"}
conn.Do("RPUSH","TEST","x","y") // This works
conn.Do("RPUSH", "TEST", arr) //This does not work
Ram
  • 1,155
  • 13
  • 34

2 Answers2

2

I don't have the library but from what I saw on their documentation, I guess that this should work:

conn.Do("RPUSH", arr...)

... is a parameter operator that unpacks the elements of your slice and passes as them separate arguments to a variadic function, which would be the same as this:

arr := []string{"TEST", "a", "b", "c", "d"}

conn.Do("RPUSH", "TEST", arr[0], arr[1], arr[2], arr[3])

More information can be found on variadic function in go in this very complete article

Ullaakut
  • 3,554
  • 2
  • 19
  • 34
  • args := []interface{"TEST"} Gives me an error unexpected literal "TEST", expecting method or interface name – Ram Aug 12 '18 at 04:26
  • @ThunderCat yeah wasn't sure about that. In the end then, he just needs to add his `TEST` value to the `arr` string as well. Editing the answer, thanks – Ullaakut Aug 12 '18 at 05:30
1

Build a slice of the arguments and call the variadic function with those arguments:

 args := []interface{"TEST")
 for _, v := range arr {
   args = append(args, v)
 }
 conn.Do("RPUSH", args...)

The Args helper does the same thing with a single line of application code:

 conn.Do("RPUSH", edis.Args{}.Add("TEST").AddFlat(arr)...)
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242