英文:
Is it possible to "partially apply" variadic functions in go?
问题
给定一个声明为
func foo(bars ...string) {
// ...
}
我想这样调用它:
bar1 := "whiskey bar"
rest := []string{"vodka bar", "wine bar"}
foo(bar1, rest...)
但是这段代码无法编译;最后一行会出现以下错误信息:
have (string, []string...)
want (...[]string)
有没有一种方法可以声明一个可变参数函数,使其可以接受零个或多个值作为参数,并且可以接受零个或一个值的数组(在最后)?
英文:
Given a function declared as
func foo(bars ...string) {
// ...
}
I'd like to call this like so:
bar1 := "whiskey bar"
rest := []string{"vodka bar", "wine bar"}
foo(bar1, rest...)
but this doesn't compile; the last line errors with this message:
have (string, []string...)
want (...[]string)
Is there a way I can declare a variadic function so that it can be called with both zero or more parameters that are values, and zero or one array of values (at the end)?
答案1
得分: 1
你需要将签名更改为func foo(some string, bars ...string)
,如文档中所述。更多信息请参考playground链接:https://play.golang.org/p/xlsCKzhj5y
英文:
You'd have to change the signature to func foo(some string, bars ...string)
as explained in the docs. More in the playground: https://play.golang.org/p/xlsCKzhj5y
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论