将golang中的`deepEqual`函数的`interface{}`类型转换为整数类型。

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

golang deepEqual interface{} to integer

问题

我正在使用redigo Redis库,并检查一个键是否已经存在于Redis集合中。我使用Redis命令SISMEMBER通过redigo的Do方法来执行,该方法返回一个接口。它是使用Do执行的命令的响应。对于SISMEMBER命令,响应是10。在这个特定的情况下,响应是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))

huangapple
  • 本文由 发表于 2016年12月20日 06:04:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/41231767.html
匿名

发表评论

匿名网友

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

确定