gomodule/redigo how can I push multiple keys to redis

3k Views Asked by At

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
2

There are 2 best solutions below

2
On

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

0
On

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