Go语言如何访问{interface{} | []interface{}}的索引?

huangapple go评论62阅读模式
英文:

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.
Go语言如何访问{interface{} | []interface{}}的索引?

答案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)
}

huangapple
  • 本文由 发表于 2022年1月26日 18:51:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70862276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定