go - 如何将 interface{} 保存的数据转换为 slice(当 interface{} 的数据结构已知时)?
问题描述
我从一个apiFunc()
返回interface{}
.
我知道在这种特定情况下,返回的数据是struct
诸如
type Data struct {
hello string
world int
}
我不知道切片有多大(API 可以发送一个包含一个或 100 个此类实体的 JSON 数组)。
我应该如何声明变量myData
,使其成为 的一部分Data
,由 的返回值组成apiFunc()
?
我知道
ret := apiFunc()
myData := ret.([]Data)
不起作用(它会恐慌interface conversion: interface {} is []interface {}, not []main.Data
)
解决方案
此代码有效:
package main
import (
"fmt"
)
type Data struct {
hello string
world int
}
func apiFunc() interface{} {
return []Data{{hello: "first hello", world: 1}, {hello: "second hello", world: 2}}
}
func main() {
ret := apiFunc()
fmt.Println(ret.([]Data))
}
去游乐场链接: https: //play.golang.org/p/SOGr6Fj-wO5
确保您apiFunc()
实际返回的是Data
切片而不是interface
切片
如果是接口切片,则需要执行以下操作:
package main
import (
"fmt"
)
type Data struct {
hello string
world int
}
func apiFunc() interface{} {
toReturn := make([]interface{}, 2)
toReturn[0] = Data{hello: "first hello", world: 1}
toReturn[1] = Data{hello: "second hello", world: 2}
return toReturn
}
func main() {
ret := apiFunc()
interfaceSlice := ret.([]interface{})
dataSlice := make([]Data, len(interfaceSlice))
for index, iface := range interfaceSlice {
dataSlice[index] = iface.(Data)
}
fmt.Println(dataSlice)
}
去游乐场链接: https: //play.golang.org/p/TsfMuKj7nZc
推荐阅读
- laravel - 图像未显示在 laravel 6 的刀片中
- spring-boot - 从 application.properties 读取的属性返回 null
- javascript - 自动插入新 React 组件的方法,即“可插入扩展”
- javascript - 如何从第二个应用程序调用表单并执行操作?
- javascript - 在尝试从索引文件中使用 JSX react/react-in-jsx-scope 时,“React”必须在范围内吗?
- javascript - 同时使用 $(this) 和 addClass/removeClass 来显示/隐藏底部导航栏的内容
- node.js - node js express 无法发布 - 获取无法发布错误消息
- django - Django设置两个模型字段之间的关系
- java - Java/Kotlin UDP 数据报
- javascript - AWS cloudwatch中存在登录但不返回日志