如何将接口{}保存的数据转换为切片(当接口{}的数据结构已知时)?

我从一个函数接收数据,该函数返回一个.apiFunc()interface{}

我知道在这种特定情况下,返回的数据是诸如struct

type Data struct {
    hello string
    world int}

我不知道切片有多大(API可以发送一个或100个此类实体的JSON数组)。

我应该如何声明变量myData,以便它是数据切片,由apiFunc()的返回值组成?

我知道那件事

ret := apiFunc()
myData := ret.([]Data)

不起作用(它恐慌与interface conversion: interface {} is []interface {}, not []main.Data)


长风秋雁
浏览 94回答 1
1回答

当年话下

此代码的工作原理:package mainimport (    "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()Datainterface如果它是接口切片,则需要执行以下操作:package mainimport (    "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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go