英文:
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)...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论