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

沃杰

我从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

曲奇04

此代码有效:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章