英文:
Go lang accessing {interface{} | []interface{}] 's index?
问题
我在接口方面遇到了一些麻烦,由于这个问题涉及到很多行代码,我无法分享任何代码。所以这就是问题,我需要访问这些 []interface{} 元素,但是它给我一个错误,说 (interface{}) 不支持索引。任何帮助都将是非常好的。我现在被卡住了。
英文:
I have a little bit trouble with interfaces, ı can not share any code cause of this problem result of many lines of code. So here is the problem , I need to access this []interface{} elements, but it gives me an error like (interface{}) does not support indexing any help would be great. I'm stuck now.
答案1
得分: 0
你需要使用类型开关来确定接口的底层类型。参见: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("这是一个映射。a: %+v\n", v["a"])
case []interface{}:
fmt.Printf("这是一个切片,长度为:%d,v[0] 是:%+v,类型为:%T\n", len(v), v[0], v[0])
default:
fmt.Printf("这是 %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)
}
这段代码展示了如何使用类型开关来确定接口的底层类型,并根据类型执行相应的操作。
英文:
you need a type switch to determine what is the interface underlying type.
See: https://go.dev/tour/methods/16
Example: (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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论