passing array or slice into variable args function in golang

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

passing array or slice into variable args function in golang

问题

filepath.Join方法接受一个...string参数,但我有一个[]string,我想传入。当我尝试这样做时,我会得到以下错误:

无法将append(elems, spadePath)(类型为[]string)作为filepath.Join的参数中的string类型使用

有没有一种方法可以在[]type...type之间进行转换?

英文:

filepath.Join method takes in a ...string argument but I have a []string that I would like pass in. When I attempt to do this I get the following error:

cannot use append(elems, spadePath) (type []string) as type string in argument to filepath.Join

Is there a way to convert between a []type and a ...type?

答案1

得分: 14

发现一种方法可以通过在作为参数传递时,在切片后面添加...来实现这一点。

例如,我最初尝试调用以下代码,但出现了错误:

filepath.Join(append(elems, basePath))

但是我通过在参数中添加...进行了修正:

filepath.Join(append(elems, basePath)...)
英文:

Found a way to do this by appending the ... to your slice when being passed in as an argument.

For example, I was originally trying to call make the following call which was yielding the error:

filepath.Join(append(elems, basePath))

but I corrected it by appending ... in the argument:

filepath.Join(append(elems, basePath)...)

huangapple
  • 本文由 发表于 2015年8月14日 02:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/31995367.html
匿名

发表评论

匿名网友

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

确定