Go错误:无法将参数(类型为[]string)作为参数中的字符串类型使用。

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

Go error: Cannot use argument (type []string) as type string in argument

问题

尝试熟悉Go语言。我想做这样的事情:

func validation(){
    headers := metadata.New(map[string]string{"auth":"","abc":"","xyz":""})
    token := headers["auth"]
    
    data.Add("cookie", token)
}

我得到了以下错误:cannot use token (type []string) as type string in argument to data.Add。这个错误与我在函数内部使用的metadata(map)有关吗?

英文:

Trying to get acquainted with go. I want to do something like this:

func validation(){
    headers := metadata.New(map[string]string{"auth":"", "abc": "", "xyz" : ""})
    token := headers["auth"]
    
    data.Add("cookie", token)
}

I am getting the following error : cannot use token (type []string) as type string in argument to data.Add. Has this error got to do anything with the metadata(map) I have inside the function?

答案1

得分: 7

Token是一个[]string类型的变量,而Add方法的第二个参数是一个string类型的变量。假设你想要获取切片的第一个元素,并且确保该切片至少有一个元素,可以使用以下代码:

data.Add("cookie", token[0])

如果你不确定切片中是否至少有一个元素,可以使用if语句进行保护:

if len(token) > 0 {
   data.Add("cookie", token[0])
} else {
   // 处理缺失值
}
英文:

Token is a []string and the 2nd argument to Add is a string. Assuming that you want the first element of the slice and the slice is guaranteed to have at least one element, use this:

data.Add("cookie", token[0])

If you don't know that there's at least one element in the slice, then protect with an if:

if len(token) > 0 {
   data.Add("cookie", token[0])
} else {
   // handle missing value
}

huangapple
  • 本文由 发表于 2017年2月10日 06:58:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/42148510.html
匿名

发表评论

匿名网友

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

确定