1 回答
TA贡献1891条经验 获得超3个赞
您需要一个类型开关来确定接口底层类型是什么。见:https ://go.dev/tour/methods/16
示例:(https://go.dev/play/p/gSRuHBoQYah):
package main
import (
"encoding/json"
"fmt"
"log"
)
func printInterface(o interface{}) {
switch v := o.(type) {
case map[string]interface{}:
fmt.Printf("this is a map. a: %+v\n", v["a"])
case []interface{}:
fmt.Printf("this is a slice, len: %d, v[0] is: %+v, type: %T\n", len(v), v[0], v[0])
default:
fmt.Printf("this is %T\n", v)
}
}
func main() {
var result1 interface{}
listOfObjects := `[{"a":1}, {"a":2}]`
if err := json.Unmarshal([]byte(listOfObjects), &result1); err != nil {
log.Fatal(err)
}
printInterface(result1)
var result2 interface{}
singleObject := `{"a":1, "b":2}`
if err := json.Unmarshal([]byte(singleObject), &result2); err != nil {
log.Fatal(err)
}
printInterface(result2)
}
- 1 回答
- 0 关注
- 129 浏览
添加回答
举报