简体   繁体   中英

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

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM