设置golang变量

huangapple go评论80阅读模式
英文:

golang variable setting

问题

我需要在我的包的开头设置一个变量,稍后将使用parseFiles()填充该变量,但我不确定如何设置该变量,因为它不是字符串、整数或类似的通用类型。我该如何设置变量,而不必添加一些任意的名称来设置它?

<!-- language: lang-go -->

var templatefiles = template.New(&quot;foo&quot;) // 我只是为了设置变量而不得不使用New(&quot;foo&quot;)

// 稍后将文件添加到原始变量
templatefiles.New(&quot;template name&quot;).Parse(&quot;Template text here&quot;)
英文:

I need to set a variable at the beginning of my package that will later on be populated with parseFiles() but im not sure how to set the variable considering its not a string or int or anything generic like that. How would i set the variable without having to add some arbitrary name in there just to set it?

<!-- language: lang-go -->

var templatefiles = template.New(&quot;foo&quot;) // Im having to do New(&quot;foo&quot;) just to set the variable

// Later on adding files to original variable
templatefiles.New(&quot;template name&quot;).Parse(&quot;Template text here&quot;)

答案1

得分: 5

你只需要将= template.New("foo")替换为返回的类型。在这种情况下:

var templatefiles *template.Template // html/template.New()的返回类型

templatefiles现在是一个全局变量,它包含一个指向类型template.Template的空指针。

英文:

You just need to replace = template.New(&quot;foo&quot;) with the type returned. In this case:

var templatefiles *template.Template // the return type of html/template.New()

templatefiles is now a global variable that contains a nil pointer to a type template.Template.

huangapple
  • 本文由 发表于 2012年10月12日 06:11:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/12849349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定