map[string]interface{}代碼示例

知識(shí)

interface{} 可以代表任意類(lèi)型
interface{} 就是一個(gè)空接口,所有類(lèi)型都實(shí)現(xiàn)了這個(gè)接口,所以它可以代表所有類(lèi)型

代碼

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)

}

編譯運(yùn)行

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

參考文檔

Go語(yǔ)言嵌套Map類(lèi)型 http://blog.ninja911.com/blog-show-blog_id-76.html
解析(map[string]interface{})數(shù)據(jù)格式并打印出數(shù)據(jù) 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/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容