dtnat80842 2012-09-27 20:49
浏览 544
已采纳

redigo,SMEMBERS,如何获取字符串

I am redigo to connect from Go to a redis database. How can I convert a type of []interface {}{[]byte{} []byte{}} to a set of strings? In this case I'd like to get the two strings Hello and 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
", 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?
}
  • 写回答

3条回答 默认 最新

  • dongqiongjiong4740 2012-09-28 06:14
    关注

    Looking at the source code for 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're using MultiBulk:

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

    This gives a reply of multiple interface{} 's in a slice: []interface{}

    Before an untyped interface{} you have to assert its type like so:

    x.(T)

    Where T is a type (eg, int, string etc.)

    In your case, you have a slice of interfaces (type: []interface{}) so, if you want a string, you need to first assert that each one has type []bytes, and then cast them to a string eg:

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

    Here's an example: http://play.golang.org/p/ZifbbZxEeJ

    You can also use a type switch to check what kind of data you got back:

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

    Or, as someone mentioned, use the built in redis.String etc. methods which will check and convert them for you.

    I think the key is, each one needs to be converted, you can't just do them as a chunk (unless you write a method to do so!).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改