Redigo, SMEMBERS, how to get rows

I am redigo to connect from Go to the redis database. How to convert a type []interface {}{[]byte{} []byte{}}to a set of strings? In this case, I would like to get two lines Helloand World.

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
)

func main() {
    c, err := redis.Dial("tcp", ":6379")
    defer c.Close()
    if err != nil {
        fmt.Println(err)
    }
    c.Send("SADD", "myset", "Hello")
    c.Send("SADD", "myset", "World")
    c.Flush()
    c.Receive()
    c.Receive()

    err = c.Send("SMEMBERS", "myset")
    if err != nil {
        fmt.Println(err)
    }
    c.Flush()
    // both give the same return value!?!?
    // reply, err := c.Receive()
    reply, err := redis.MultiBulk(c.Receive())
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%#v\n", reply)
    // $ go run main.go
    // []interface {}{[]byte{0x57, 0x6f, 0x72, 0x6c, 0x64}, []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f}}
    // How do I get 'Hello' and 'World' from this data?
}
+5
source share
3 answers

Looking at the source code of the module, you can see the type signature returned from Receive will be:

func (c *conn) Receive() (reply interface{}, err error)

and in your case you are using MultiBulk :

func MultiBulk(v interface{}, err error) ([]interface{}, error)

This gives a few interface{}slice answer :[]interface{}

Before untyped, interface{}you must validate your type as follows:

x (T)

Where T- the type (eg int, stringetc.)

(type: []interface{}), , string, , [] , , :

for _, x := range reply {
    var v, ok = x.([]byte)
    if ok {
        fmt.Println(string(v))
    }
}

: http://play.golang.org/p/ZifbbZxEeJ

, , :

http://golang.org/ref/spec#Type_switches

for _, y := range reply {
    switch i := y.(type) {
    case nil:
        printString("x is nil")
    case int:
        printInt(i)  // i is an int
    etc...
    }
}

, , redis.String .., .

, , , ( !).

+4

// String is a helper that converts a Redis reply to a string. 
//
//  Reply type      Result
//  integer         format as decimal string
//  bulk            return reply as string
//  string          return as is
//  nil             return error ErrNil
//  other           return error
func String(v interface{}, err error) (string, error) {

redis.String (v interface{}, err error) (string, error)

reply, err := redis.MultiBulk(c.Receive())

s, err := redis.String(redis.MultiBulk(c.Receive()))
+8

To make an advertisement for my own product, just take a look at http://cgl.tideland.biz . There you will also find my Redis client. It supports each team, as well as several teams and pub / sub. As a return value, you get a result set that allows you to conveniently get one or more return values ​​or hashes along with methods for converting to native Go types.

+2
source

All Articles