【问题标题】:What does an empty map of interfaces do in a golang function?在 golang 函数中,一个空的接口映射有什么作用?
【发布时间】:2015-06-12 00:45:09
【问题描述】:

我正在阅读an article on golang templates,这出现在示例代码中。

func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
    // Ensure the template exists in the map.
    tmpl, ok := templates[name]
    if !ok {
        return fmt.Errorf("The template %s does not exist.", name)
    }

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    tmpl.ExecuteTemplate(w, "base", data)

    return nil
}

我不明白的部分是函数声明中的参数data

data map[string]interface{}

我对go中的接口只有非常基本的了解,但不知道为什么会这样使用。

【问题讨论】:

    标签: go


    【解决方案1】:

    interface{} 类似于 C 中的 (void*) 或 Java 中的 Object,表示映射中可以存储任何类型的值。

    【讨论】:

    • 但是查看代码不会data 只是保持空白吗?为什么不传入nil
    • 是什么让你觉得它是由调用者提供的时候是空的?
    • :O 我不知道我是怎么错过的。谢谢哈哈
    • 我是否也可以假设编写代码的人犯了一个小错误?他们正在传递数据,这是一个地图,作为 ExecuteTemplate 的第三个参数,但在文档中它不是地图,它只是 data interface{}
    • 作为那篇文章的作者:@ChristopherCurrie 是正确的。此外,我们传入map[string]interface{} 的原因是,我们可以在将数据传递给模板时命名我们的数据,然后在模板本身中按名称引用它——有时可能是@987654328 @,其他时候可能是.post,等等。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2016-06-15
    • 2017-12-11
    • 1970-01-01
    • 2015-06-06
    • 2019-03-20
    相关资源
    最近更新 更多