如何将界面{}转换为地图 [英] How to convert interface{} to map
问题描述
我正在尝试创建一个可以接受以下功能的函数
I am trying to create a function that could accept following
*struct
[]*struct
map[string]*struct
这里的struct可以是任何结构,而不仅仅是特定的。
将接口转换为 * struct
或 [] * struct
可以正常工作。
但是给map给出了错误。
Here struct could be any struct not just a specific one.
Converting interface to *struct
or []*struct
is working fine.
But giving error for map.
在反射之后,它表明它是map [],但是尝试遍历范围时却给出了错误。
After reflect it shows it is map[] but giving error when try to iterate over range.
这里是代码
package main
import (
"fmt"
"reflect"
)
type Book struct {
ID int
Title string
Year int
}
func process(in interface{}, isSlice bool, isMap bool) {
v := reflect.ValueOf(in)
if isSlice {
for i := 0; i < v.Len(); i++ {
strct := v.Index(i).Interface()
//... proccess struct
}
return
}
if isMap {
fmt.Printf("Type: %v\n", v) // map[]
for _, s := range v { // Error: cannot range over v (type reflect.Value)
fmt.Printf("Value: %v\n", s.Interface())
}
}
}
func main() {
b := Book{}
b.Title = "Learn Go Language"
b.Year = 2014
m := make(map[string]*Book)
m["1"] = &b
process(m, false, true)
}
有什么方法可以转换 interface {}
来映射和迭代或获取其元素。
Is there any way to convert interface{}
to map and iterate or get it's elements.
推荐答案
如果地图值可以是任何类型,则使用反射来遍历地图:
If the map value can be any type, then use reflect to iterate through the map:
if v.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
strct := v.MapIndex(key)
fmt.Println(key.Interface(), strct.Interface())
}
}
如果存在少量已知的结构类型,则类型可以使用开关:
If there's a small and known set of struct types, then a type switch can be used:
func process(in interface{}) {
switch v := in.(type) {
case map[string]*Book:
for s, b := range v {
// b has type *Book
fmt.Printf("%s: book=%v\n" s, b)
}
case map[string]*Author:
for s, a := range v {
// a has type *Author
fmt.Printf("%s: author=%v\n" s, a)
}
case []*Book:
for i, b := range v {
fmt.Printf("%d: book=%v\n" i, b)
}
case []*Author:
for i, a := range v {
fmt.Printf("%d: author=%v\n" i, a)
}
case *Book:
fmt.Ptintf("book=%v\n", v)
case *Author:
fmt.Printf("author=%v\n", v)
default:
// handle unknown type
}
}
这篇关于如何将界面{}转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!