map interface{}
package main import ( "fmt" ) func main() { mapInterface := make(map[interface{}]interface{}) mapString := make(map[string]string) mapInterface["k1"] = 1 mapInterface[3] = "hello" mapInterface["world"] = 1.05 for key, value := range mapInterface { strKey := fmt.Sprintf("%v", key) strValue := fmt.Sprintf("%v", value) mapString[strKey] = strValue } fmt.Printf("%#v", mapString) }
root@ubuntu:~/go_learn/example.com/hello# go build -o hello . root@ubuntu:~/go_learn/example.com/hello# ./hello map[string]string{"3":"hello", "k1":"1", "world":"1.05"}
package main import "fmt" func main() { m := make(map[string]interface{}) m["int"] = 123 m["string"] = "hello" m["bool"] = true for _, v := range m { switch v.(type) { case string: fmt.Println(v, "is string") case int: fmt.Println(v, "is int") default: fmt.Println(v, "is other") } } fmt.Println(m) }
root@ubuntu:~/go_learn/example.com/hello# ./hello 123 is int hello is string true is other map[bool:true int:123 string:hello]
结构体转map[string]interface{}