英文:
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...)
英文:
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...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论