如何使用可变参数包装函数

Chr*_*son 1 go

在Go中,可以在函数中使用...表示法为最终参数添加前缀,以指示它是可变参数.

template.ParseFiles就是这样一个函数:

func (t *Template) ParseFiles(filenames ...string) (*Template, error)
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建自己的函数,它设置了我的模板的各种常见功能,我希望调用函数传入需要解析的文件列表,但我不知道如何.

例如,如果我的代码看起来像这样:

type templateMap map[string]*template.Template
func (tmpl templateMap) AddTemplate(name string, files ...string) {
    tmpl[name] = template.Must(template.ParseFiles(files)).Delims("{@","@}")
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

cannot use files (type []string) as type string in function argument
Run Code Online (Sandbox Code Playgroud)

如何包装可变参数?

Jam*_*dge 5

要传递一个切片来代替函数的可变参数,只需将其后缀为....因此,在您的示例代码中,您需要:

tmpl[name] = template.Must(template.ParseFiles(files...)).Delims("{@","@}")
Run Code Online (Sandbox Code Playgroud)

以下是该概念的一个简单示例:http://play.golang.org/p/TpYNxnAM_5