美文网首页
map[string]interface{}代码示例

map[string]interface{}代码示例

作者: 莫名FCJ | 来源:发表于2017-11-03 11:45 被阅读149次

知识

interface{} 可以代表任意类型
interface{} 就是一个空接口,所有类型都实现了这个接口,所以它可以代表所有类型

代码

https://github.com/fengchunjian/goexamples/tree/master/map_interface

//null_interface.go
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)

}

编译运行

go build null_interface.go
./null_interface 
123 is int
hello is string
true is other
map[int:123 string:hello bool:true]

参考文档

Go语言嵌套Map类型 http://blog.ninja911.com/blog-show-blog_id-76.html
解析(map[string]interface{})数据格式并打印出数据 http://www.codeweblog.com/%E8%A7%A3%E6%9E%90-map-string-interface-%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F%E5%B9%B6%E6%89%93%E5%8D%B0%E5%87%BA%E6%95%B0%E6%8D%AE/

相关文章

网友评论

      本文标题:map[string]interface{}代码示例

      本文链接:https://www.haomeiwen.com/subject/viqtmxtx.html