我有value [token code id_token] from map, value of map type []interface{}
resp := result["response_types"]
resp istype []interface{}
.
我需要将其转换为:clientobj.ResponseTypes
type client struct{
ResponseTypes sqlxx.StringSlicePipeDelimiter `json:"response_types" db:"response_types"`
}
package sqlxx
type StringSlicePipeDelimiter []string
有转换吗?
要将[]inteface{}
转换为[]string
,只需遍历片并使用类型断言:
// given resp is []interface{}
// using make and len of resp for capacity to allocate the memory in one go
// instead of having the runtime reallocate memory several times when calling append
str := make([]string, 0, len(resp))
for _, v := range resp {
if s, ok := v.(string); ok {
str = append(str, s)
}
}
这里真正的问题是,您最初是如何得到[]interface{}
类型的变量的。你就没有办法避免吗?看看StringSlicePipeDelimiter
类型本身,它在这里有Scan
方法(从数据库扫描值到类型所需的接口的一部分),所以我不禁想知道为什么要使用[]interface{}
类型的间歇变量