gin.H 是什么类型

文章目录

    经常在 golang gin 的代码中看到这样返回 json 结构的数据:

    c.JSON(http.StatusOK, gin.H{
        "domain": "sunzhongwei.com",
        "name": "大象笔记",
    })
    

    从 gin 的源码 utils.go 中,可以看到

    // H is a shortcut for map[string]interface{}
    type H map[string]interface{}
    

    map 我能理解,等同于 python 的字典 dict。所以 H 大概就是 Hash Table 的首字母吧。
    但是,interface 是什么呢?

    golang map 的基本使用方法

    Go provides a built-in map type that implements a hash table.

    语法:map[KeyType]ValueType

    例子:

    info := map[string]int{
        "ago": 18,
        "weight":   168,
    }
    

    golang interface 是做什么的

    interface 提供了一个标准,满足了 interface 里定义的方法的,就可以归为一个 interface 类别。

    由于Go语言中任何对象实例都满足空接口interface{},所以interface{}看起来像是可以指向任何对象的Any类型.

    所以,定义为 map[string]interface{} 就实现了类似 python 字典的数据类型。
    key 可以是 string,而 value 则可以是任何类型。因为空 interface 能被所有类型满足。

    参考

    https://ddcode.net/2019/05/11/the-gin-framework-is-full-of-gin-h-what-does-it-mean/

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式