如何将 []string 转换为 …string?

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

How to convert []string to ...string

问题

我想要一个函数来扫描文件夹并找到所有的模板文件。然后调用template.ParseFiles来解析所有的模板。我使用var tmplPathList []string来记录所有的模板,并将tmplPathList传递给template.ParseFiles()

func ParseFiles(filenames ...string) (*Template, error)使用...string作为参数。编译错误显示cannot use tmplPathList (type []string) as type string in argument to "html/template".ParseFiles

我该如何将[]string转换为...string

var tmplPathList []string
for _, file := range tmplList {
    tmplPathList = append(tmplPathList, dir+file.Name())
}
templates = template.Must(template.ParseFiles(tmplPathList...))
英文:

I want to have a func to scan the folder and find all the template file. Then call template.ParseFiles to parse all the templates. I use the var tmplPathList []string to record all the templates, and pass tmplPathList to template.ParseFiles().

The func ParseFiles(filenames ...string) (*Template, error) use ... string as parameter. The compile error cannot use tmplPathList (type []string) as type string in argument to "html/template".ParseFiles

How can I convert []string to ... string?

var tmplPathList []string
for _, file := range tmplList {
	tmplPathList = append(tmplPathList, dir + file.Name())
}
templates = template.Must(template.ParseFiles(tmplPathList))

答案1

得分: 5

你可以在调用函数时,在变量名后面添加...,以允许使用切片值作为可变参数:

template.ParseFiles(tmplPathList...)

在play.golang.org上查看示例

英文:

You can append ... to the variable-name when calling the function to allow the slices values to be used as varargs-parameters:

template.ParseFiles(tmplPathList...)

Demo on play.golang.org

huangapple
  • 本文由 发表于 2017年2月25日 13:42:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/42452415.html
匿名

发表评论

匿名网友

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

确定