Ram
Ram

Reputation: 1193

gomodule/redigo how can I push multiple keys to redis

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

Upvotes: 2

Views: 3236

Answers (2)

Ullaakut
Ullaakut

Reputation: 3734

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

Upvotes: 2

Thundercat
Thundercat

Reputation: 120989

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

Upvotes: 1

Related Questions