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

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

How do I wrapper a function with variadic parameters

问题

在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

我该如何包装可变参数?

英文:

In Go, it's possible to prefix the final parameter in a function with the ... notation to indicate it is a variadic parameter.

template.ParseFiles is one such function:

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

I am trying to create a function of my own which sets up various common features of my templates and I'd like the calling function to pass in the list of files that need to be parsed but I'm not sure how.

For example if my code looked like this:

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

I get an error:

cannot use files (type []string) as type string in function argument

How do I wrapper variadic parameters?

答案1

得分: 5

将切片作为函数的可变参数传递,只需在切片后面加上...。所以在你的示例代码中,你应该这样写:

tmpl[name] = template.Must(template.ParseFiles(files...)).Delims("{@","@}")

这里有一个简单的示例:http://play.golang.org/p/TpYNxnAM_5

英文:

To pass a slice in place of the variadic argument of a function, simply suffix it with .... So in your example code, you would instead want:

tmpl[name] = template.Must(template.ParseFiles(files...)).Delims("{@","@}")

Here is a simple example of the concept: http://play.golang.org/p/TpYNxnAM_5

huangapple
  • 本文由 发表于 2014年6月19日 08:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/24297128.html
匿名

发表评论

匿名网友

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

确定