【问题标题】:Go error: Cannot use argument (type []string) as type string in argumentGo 错误:不能在参数中使用参数(类型 [] 字符串)作为类型字符串
【发布时间】:2017-02-09 22:58:37
【问题描述】:

尝试熟悉 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。这个错误是否与函数内部的元数据(地图)有关?

【问题讨论】:

标签: go grpc


【解决方案1】:

Token 是 []string,Add 的第二个参数是 string。假设你想要切片的第一个元素并且切片保证至少有一个元素,使用这个:

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

如果您不知道切片中至少有一个元素,则使用 if 进行保护:

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

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2021-09-20
    • 2021-10-21
    • 2021-10-13
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多