在Go语言中,是否可以“部分应用”可变参数函数?

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

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

huangapple
  • 本文由 发表于 2017年5月2日 19:03:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43736264.html
匿名

发表评论

匿名网友

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

确定