英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论