1 回答
TA贡献1890条经验 获得超9个赞
此代码的工作原理:
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()Datainterface
如果它是接口切片,则需要执行以下操作:
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
- 1 回答
- 0 关注
- 89 浏览
添加回答
举报