从 Redis 服务器获取列表元素,将类型从 []interface{} 转换为 []string。

huangapple go评论74阅读模式
英文:

getting list elements from a redis server ,from []interface{} to []string

问题

我正在尝试使用redigo库将Redis与Go连接起来,redis-server已经在运行。

我想创建一个字符串列表,追加一个字符串,然后从服务器获取所有元素并将它们打印出来。

这是我尝试的代码:

package main

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

func main() {
	c, err := redis.Dial("tcp", ":6379")
	check(err)
	defer c.Close()
	_, err = c.Do("LPUSH", "bars", "foo")
	check(err)

	n, err := redis.Values(c.Do("LRANGE", "bars", 0, 10))
	check(err)
	fmt.Println(n)
}

func check(err error) {
	if err != nil {
		panic(err)
	}
}

我得到的输出是[[102 111 111]],而不是foo,看起来是因为Values返回的是[]interface{}类型。

我该如何将[]interface{}(即Values的返回类型)转换为[]string

英文:

I trying to connect [tag:redis] with [tag:go] using redigo, redis-server is running.

I want to create a list of strings, append one string , then get all the elements from the server and print them out.

this , what I tried

package main

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

func main() {
	c, err := redis.Dial("tcp", ":6379")
	check(err)
	defer c.Close()
	_, err = c.Do("LPUSH", "bars", "foo")
	check(err)

	n, err := redis.Values(c.Do("LRANGE", "bars", 0, 10))
	check(err)
	fmt.Println(n)
}

func check(err error) {
	if err != nil {
		panic(err)
	}
}

I get [[102 111 111]] printed instead of foo, it seems that

How can I convert []interface{} (Values return type) to []string ?

答案1

得分: 4

我对你使用的包不熟悉,但是文档建议使用redis.Strings()而不是redis.Values()可以实现你想要的效果:

Strings是一个辅助函数,将多个批量命令的回复转换为[]string类型。如果err不等于nil,则Strings返回nil, err。如果其中一个批量项不是批量值或nil,则Strings返回一个错误。

英文:

I'm not familiar with the package you're using, but the documentation suggests that using redis.Strings() instead of redis.Values() will do what you're after:

> Strings is a helper that converts a multi-bulk command reply to a []string. If err is not equal to nil, then Strings returns nil, err. If one if the multi-bulk items is not a bulk value or nil, then Strings returns an error.

答案2

得分: -2

你可以尝试使用这个适用于Golang的Redis客户端:

https://github.com/xuyu/goredis

从 Redis 服务器获取列表元素,将类型从 []interface{} 转换为 []string。

英文:

maybe you can try this redis client for golang:

https://github.com/xuyu/goredis

从 Redis 服务器获取列表元素,将类型从 []interface{} 转换为 []string。

huangapple
  • 本文由 发表于 2013年10月12日 11:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/19330166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定