1 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
此代碼的工作原理:
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))
}
去游樂(lè)場(chǎng)鏈接: https://play.golang.org/p/SOGr6Fj-wO5
確保實(shí)際返回的是切片,而不是切片apiFunc()Datainterface
如果它是接口切片,則需要執(zhí)行以下操作:
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)
}
去游樂(lè)場(chǎng)鏈接: https://play.golang.org/p/TsfMuKj7nZc
- 1 回答
- 0 關(guān)注
- 109 瀏覽
添加回答
舉報(bào)