【问题标题】:Convert []interface{} into type []string [duplicate]将 []interface{} 转换为类型 []string [重复]
【发布时间】:2021-05-11 23:56:16
【问题描述】:

我有来自地图的值 [令牌代码 id_token],地图类型的值 []interface{}

resp := result["response_types"]

resp 是type []interface{}

我需要将其转换为:clientobj.ResponseTypes

type client struct{
    ResponseTypes sqlxx.StringSlicePipeDelimiter `json:"response_types" db:"response_types"`
}

在 sqlxx 包中

package sqlxx
type StringSlicePipeDelimiter []string

有转换的吗?

【问题讨论】:

  • 请打开这个问题,这个问题不能重复。我通过 marshal 和 unmarshal 解决它。我想分享我的答案。

标签: go


【解决方案1】:

要将[]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 方法(将值从数据库扫描到类型所需的接口的一部分)right here,所以我不禁想知道你为什么使用[]interface{} 类型的间歇变量

【讨论】:

  • 我使用 []interface{} 类型的间歇变量,因为我从 Aerospike 数据中获取数据
  • 它作为 aerospike.BinMap 的类型返回,结果 ["response_types"] 作为 []interface{} 返回值,我需要将其转换为 StringSlicePipeDelimiter。
猜你喜欢
  • 1970-01-01
  • 2015-01-14
  • 2022-07-06
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 2020-04-24
  • 2021-05-26
相关资源
最近更新 更多