How do typecast a type in Go

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

How do typecast a type in Go

问题

我正在尝试创建一个递归例程,用于打印复杂 JSON 的元素。

func printMap(m map[string]interface{}) {
    for k, v := range m {
        typ := reflect.ValueOf(v).Kind()
        if typ == reflect.Map {
            printMap(v)
        } else {
            fmt.Println(k, v)
        }
    }
}

但是我遇到了一个构建错误,提示无法将类型 v (type interface {}) 用作类型 map[string]interface{}

有没有办法进行类型转换或者其他方法可以使其正常工作?

英文:

I am trying to make a recursive routine that prints the elements of a complex json

func printMap(m map[string]interface{}) {
for k, v := range m {
	typ := reflect.ValueOf(v).Kind()
	if typ == reflect.Map {
		printMap(v)
	} else {
		fmt.Println(k, v)
	}
} }

but I get a build error
can use type v ( type interface {} ) as type map[string] interface{}

Is there a way to type cast it or someway I can get it to work?

答案1

得分: 1

使用类型断言(type assertion):

func printMap(m map[string]interface{}) {
	for k, v := range m {
		m, ok := v.(map[string]interface{}) // < -- 断言 v 是一个 map
		if ok {
			printMap(m)
		} else {
			fmt.Println(k, v)
		}
	}
}

playground 示例

英文:

Use a type assertion:

func printMap(m map[string]interface{}) {
  for k, v := range m {
    m, ok := v.(map[string]interface{}) // &lt;-- assert that v is a map
	if ok {
		printMap(m)
	} else {
		fmt.Println(k, v)
	}
  }
}

playground example

huangapple
  • 本文由 发表于 2016年10月27日 05:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/40272698.html
匿名

发表评论

匿名网友

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

确定