我的介面有點麻煩,我不能分享導致這個問題的任何代碼原因是多行代碼的結果。所以這里有問題,我需要訪問這個 []interface{} 元素,但它給了我一個錯誤,比如(interface{}) 不支持索引任何幫助都會很棒。我現在被困住了。
![Go lang 訪問 {interface{} | []interface{}] 的索引?](https://img.uj5u.com/2022/01/28/77a99bbee13b4733b455ec5fedb9103c.png)
uj5u.com熱心網友回復:
您需要一個型別開關來確定介面底層型別是什么。見: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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422102.html
標籤:
上一篇:編碼base64時的記憶體消耗
