2012-09-27 20 views
5

我是redigo從Go連接到redis數據庫。 如何將[]interface {}{[]byte{} []byte{}}類型轉換爲一組字符串?在這種情況下,我想獲得兩個字符串HelloWorldredigo,SMEMBERS,如何獲取字符串

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

回答

4

縱觀該模塊的源代碼,你可以看到type signature returned from Receive將是:

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

,並在你的情況,你使用MultiBulk

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

這給出了一個[]interface{}

在未指定類型interface{}之前,您必須爲assert its type像這樣:

X(T)

T是一種類型(例如,intstring等)

你的情況,你有接口切片(類型:[]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

或者,正如有人所提到的,使用內置的redis.String等方法將檢查和轉換它們給你。

我認爲關鍵是,每個人都需要轉換,你不能只是做一個塊(除非你寫一個方法來做!)。

8

查找範圍module source code

// 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())) 
+1

我得到以下錯誤:'redigo:字符串的意外類型,從上面的行中獲得了type [] interface {}'... – topskip

+0

@topskip:可能沒有必要說這個,因爲這個問題已經有了答案,但未解決的類型錯誤可能是因爲您插入的是接口片而不是接口。如果你已經通過一些接口枚舉並使用了redis.String,它可能會正常工作。 – bleakgadfly

2

爲我自己的產品做一些廣告:看看http://cgl.tideland.biz。你還可以找到我的Redis客戶端。它支持每個命令以及多命令和pub/sub。作爲返回值,您將得到一個結果集,它允許您方便地訪問單個或多個返回值或哈希以及用於轉換爲本機Go類型的方法。

相關問題