在Go中,可以在函数中的最终参数前面加上...表示法,以表明它是可变参数。
template.ParseFiles是这样的功能之一:
func (t *Template) ParseFiles(filenames ...string) (*Template, error)
我正在尝试创建自己的函数,该函数设置了模板的各种常用功能,并且我希望调用函数传递需要解析的文件列表,但我不确定该怎么做。
例如,如果我的代码如下所示:
type templateMap map[string]*template.Template
func (tmpl templateMap) AddTemplate(name string, files ...string) {
tmpl[name] = template.Must(template.ParseFiles(files)).Delims("{@","@}")
}
我收到一个错误:
cannot use files (type []string) as type string in function argument
如何包装可变参数?
要传递切片代替函数的可变参数,只需在后面加上...
。因此,在示例代码中,您需要:
tmpl[name] = template.Must(template.ParseFiles(files...)).Delims("{@","@}")
这是一个简单的概念示例:http : //play.golang.org/p/TpYNxnAM_5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句