如何在Go语言中导入和使用不同的同名软件包? [英] How to import and use different packages of the same name in Go language?

查看:176
本文介绍了如何在Go语言中导入和使用不同的同名软件包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import(
fmt
net / http
text / template//模板重新声明为导入的包名称
html / template//模板重新声明为导入的包名称


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

}


解决方案 div>

  import(
text / template
htemplatehtml / template//现在将它导入为模板

详细了解它在规范中。


For example, I want to use both text/template and html/template in one source file. But the code below throw errors.

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}}`)

}

解决方案

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

Read more about it in the spec.

这篇关于如何在Go语言中导入和使用不同的同名软件包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆