【问题标题】:How to import and use different packages of the same name如何导入和使用不同的同名包
【发布时间】:2012-05-11 15:01:42
【问题描述】:

例如,我想在一个源文件中同时使用 text/template 和 html/template。 但是下面的代码会抛出错误。

import (
    "fmt"
    "net/http"
    "text/template" // template redeclared as imported package name
    "html/template" // template redeclared as imported package name
)

func handler_html(w http.ResponseWriter, r *http.Request) {
    t_html, err := html.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
    t_text, err := text.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)

}

【问题讨论】:

    标签: go package


    【解决方案1】:

    Mostafa 的回答是正确的,但是需要一些解释。让我试着回答一下。

    您的示例代码不起作用,因为您尝试导入两个具有相同名称的包,即:“模板”。

    import "html/template"  // imports the package as `template`
    import "text/template"  // imports the package as `template` (again)
    

    导入是声明语句:

    • 您不能在同一范围内声明相同的名称(术语:标识符)。

    • 在 Go 中,import 是一个声明,其范围是尝试导入这些包的文件。

    • 因为不能在同一个块中声明同名变量的原因相同。

    以下代码有效:

    package main
    
    import (
        t "text/template"
        h "html/template"
    )
    
    func main() {
        t.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
        h.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
    }
    

    上面的代码为导入的同名包提供了两个不同的名称。因此,您现在可以使用两种不同的标识符:t 用于 text/template 包,h 用于 html/template 包。

    You can check it on the playground.

    【讨论】:

      【解决方案2】:
      import (
          "text/template"
          htemplate "html/template" // this is now imported as htemplate
      )
      

      阅读更多相关信息in the spec

      【讨论】:

      • JS 以 requireimport 语句的清晰性将其钉牢,比我见过的任何其他语言都要好
      • @r3wt:最好的。语言。永远!
      • 没有最好的语言,只有更适合某些问题的语言等
      猜你喜欢
      • 2022-06-10
      • 2011-04-13
      • 2014-11-21
      • 1970-01-01
      • 2018-02-26
      • 2012-12-12
      • 2016-11-18
      • 2012-08-04
      • 2012-02-14
      相关资源
      最近更新 更多