调用中的参数过多

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

Too many arguments in call

问题

我正在尝试使用mysql2redis将数据库数据加载到Redis集群中。

当我尝试使用已接受的解决方案时,即:

} else if e.Command == "HMSET" {
    // 构建一个字符串切片来保存键值对
    args := make([]string, 0, len(e.MapData) * 2)
    for k, v := range e.MapData {
        args = append(args, k, v)
    }
    _, err := redis.StringMap(client.Do("HMSET", e.Key, args...))
    checkErr(err, "hmset error:")
}

我遇到以下异常:

调用client.Do时参数过多
	拥有(string, string, []string...)
	期望(string, ...interface {})

我对Go不太熟悉,所以能否请Go专家看一下,并提供解决方案?

英文:

I'm trying to load db data to redis cluster using mysql2redis.

When i try the accepted solution, i.e.,

} else if e.Command == "HMSET" {
    // Build up a string slice to hold the key value pairs
    args := make([]string, 0, len(e.MapData) * 2)
    for k, v := range e.MapData {
        args = append(args, k, v)
    }
    _,err := redis.StringMap(client.Do("HMSET", e.Key, args...))
    checkErr(err, "hmset error:")
}

I get following exception,

too many arguments in call to client.Do
	have (string, string, []string...)
	want (string, ...interface {})

I'm a newbie when it comes to Go. So can the Go veterans take a look at this and suggest a solution?

答案1

得分: 1

在Go语言中,你可以使用切片作为可变参数。然而,这个切片必须包含你需要传递给函数的所有参数。你不能扩展一个切片并同时传递额外的参数。

因此,你的代码应该像这样:

args := make([]interface{}, 0, len(e.MapData) * 2 + 1)
args = append(args, e.Key)
for k, v := range e.MapData {
    args = append(args, k, v)
}
_, err := redis.StringMap(client.Do("HMSET", args...))
英文:

In Go you can use a slice for a variadic parameter. However, the slice must contain all the parameters you need to pass to the function. You cannot expand a slice and pass additional parameters as well.

Hence your code should be something like:

args := make([]interface{}, 0, len(e.MapData) * 2 + 1)
args = append(args, e.Key)
for k, v := range e.MapData {
    args = append(args, k, v)
}
_,err := redis.StringMap(client.Do("HMSET", args...))

huangapple
  • 本文由 发表于 2017年7月24日 18:58:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/45278840.html
匿名

发表评论

匿名网友

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

确定