英文:
golang deepEqual interface{} to integer
问题
我正在使用redigo
Redis库,并检查一个键是否已经存在于Redis集合中。我使用Redis命令SISMEMBER
通过redigo的Do
方法来执行,该方法返回一个接口。它是使用Do
执行的命令的响应。对于SISMEMBER
命令,响应是1
或0
。在这个特定的情况下,响应是0
,因为给定的键不在这个集合中。然而,当期望为true
时,reflect.DeepEqual(resp, 0)
返回false
。这不是使用DeepEqual
函数的正确方式吗?
import (
"fmt"
"reflect"
"github.com/garyburd/redigo/redis"
)
func main() {
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
resp, err := conn.Do("SISMEMBER", "mySet", "Hello")
if reflect.DeepEqual(resp, 0) {
fmt.Println("record doesn't exist")
}
}
英文:
I'm using the redigo
redis library, and checking if a key is already present in a redis set
. I'm using the redis command SISMEMBER
via the redigo's Do
method which returns an interface. It is the response of the command being executed using Do
. In case of SISMEMBER
command, the response in a 1
or 0
. and in this particular case, the response is 0
as the given key is not present in this set. however reflect.DeepEqual(resp, 0)
is returning false
when true
is expected. Is this not the correct way to use DeepEqual
function?
import (
"fmt"
"reflect"
"github.com/garyburd/redigo/redis"
)
func main() {
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
resp, err := conn.Do("SISMEMBER", "mySet", "Hello")
if reflect.DeepEqual(resp, 0) {
fmt.Println("record doesn't exist")
}
}
答案1
得分: 1
不要担心过于复杂化你的代码,你可以使用redigo的一些内置函数将响应转换为int
,然后检查键是否存在于redis中。
resp, err := redis.Int(conn.Do("SISMEMBER", "mySet", "Hello"))
if err != nil {
// 错误处理
}
if resp == 0 {
fmt.Println("记录不存在")
}
英文:
Instead of over complicate your code, you can use some build-in functions of redigo to convert the response to int
and afterward check if the key is or is not in redis.
resp, err := redis.Int(conn.Do("SISMEMBER", "mySet", "Hello"))
if err != nil {
// some error handler
}
if resp == 0 {
fmt.Println("record doesn't exist")
}
答案2
得分: 0
当我检查resp
接口的类型时,我发现它是int64
,所以适当地将0
进行类型转换,如下所示:
reflect.DeepEqual(resp, int64(0))
翻译结果:
fmt.Printf("返回类型:%T,返回值:%v\n", resp, resp)
当我检查`resp`接口的类型时,我发现它是`int64`,所以适当地将`0`进行类型转换,如下所示:
reflect.DeepEqual(resp, int64(0))
英文:
fmt.Printf("ret type: %T, ret: %v\n", resp, resp)
when I did check the type of the resp
interface, i found that it is int64
, so casting the 0
appropriately, like below, helped.
reflect.DeepEqual(resp, int64(0))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论