redigo,SMEMBERS,如何获得字符串

top*_*kip 6 go redis

我是redigo连接从Go到redis数据库.如何将一种类型转换[]interface {}{[]byte{} []byte{}}为一组字符串?在这种情况下,我想得到两个字符串HelloWorld.

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?
}
Run Code Online (Sandbox Code Playgroud)

Max*_*Max 8

查看模块源代码

// 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) {
Run Code Online (Sandbox Code Playgroud)

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

reply, err := redis.MultiBulk(c.Receive())
Run Code Online (Sandbox Code Playgroud)

用...来代替

s, err := redis.String(redis.MultiBulk(c.Receive()))
Run Code Online (Sandbox Code Playgroud)

  • 我收到以下错误:`redigo:String 的意外类型,从上面的行中得到了类型 []interface {}`... (2认同)

min*_*omi 4

查看该模块的源代码,您可以看到从 Receive 返回的类型签名将是:

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

在您的情况下,您正在使用MultiBulk

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

interface{}这给出了切片中多个 的回复:[]interface{}

在无类型之前,interface{}您必须像这样断言其类型:

x.(T)

其中T是类型(例如,intstring

在您的情况下,您有一个接口切片(类型:)[]interface{},因此,如果您想要一个接口string,您需要首先断言每个接口都有 []bytes 类型,然后它们转换为字符串,例如:

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

这是一个例子: 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...
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,正如有人提到的,使用内置的redis.String等方法,它将为您检查和转换它们。

我认为关键是,每个都需要转换,你不能只是将它们作为一个块来处理(除非你编写一个方法来这样做!)。