同じ名前の異なるパッケージをインポートして使用する方法 質問する

同じ名前の異なるパッケージをインポートして使用する方法 質問する

たとえば、1 つのソース ファイルで 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}}`)

}

ベストアンサー1

import (
    "text/template"
    htemplate "html/template" // this is now imported as htemplate
)

詳細はこちら仕様では

おすすめ記事