英文:
Go unpacking array as arguments to path.Join
问题
我想解开字符串数组并传递给path.Join函数。
package main
import (
"fmt"
"path"
)
func main() {
p := []string{"a", "b", "c"}
fmt.Println(path.Join(p...))
}
这段代码的输出结果是:
a/b/c
但是如果我像这样传递参数:
package main
import (
"fmt"
"path"
)
func main() {
p := []string{"a", "b", "c"}
fmt.Println(path.Join("d", p...))
}
它不起作用。
tmp/sandbox299218161/main.go:10: too many arguments in call to path.Join
have (string, []string...)
want (...string)
我认为我对解包有误解,有什么建议吗?
英文:
I want to unpack string array and pass to path.Join
package main
import (
"fmt"
"path"
)
func main() {
p := []string{"a", "b", "c"}
fmt.Println(path.Join(p...))
}
Output of this code is:
a/b/c
But if I pass arguments like:
package main
import (
"fmt"
"path"
)
func main() {
p := []string{"a", "b", "c"}
fmt.Println(path.Join("d", p...))
}
It doesn't work.
tmp/sandbox299218161/main.go:10: too many arguments in call to path.Join
have (string, []string...)
want (...string)
I think I have misunderstanding on unpacking, any suggestions?
答案1
得分: 10
你没有真正误解任何事情,你只是不能这样做。规范中说:
> 如果最后一个参数可以赋值给切片类型[]T
,并且在参数后面跟着...
,则它可以作为...T
参数的值传递,而不需要创建新的切片。
简而言之,p...
只能作为参数的整个可变部分使用,因为当你这样做时,它只是在函数内部将p
作为参数切片重复使用,而不是创建一个新的切片。
如果你想在开头添加一些参数,你需要先构建一个包含所有参数的切片,类似于:
p := []string{"a", "b", "c"}
p2 := append([]string{"d"}, p...)
fmt.Println(path.Join(p2...))
这样可以正常工作,并打印出"d/a/b/c"。
英文:
You're not misunderstanding anything really, you just can't do that. The spec says:
> If the final argument is assignable to a slice type []T
, it may be passed unchanged as the value for a ...T
parameter if the argument is followed by ...
. In this case no new slice is created.
In short, p...
can only be used as the entire variadic part of the arguments, because when you do that, it simply re-uses p
as the parameter slice within the function, instead of making a new one.
If you want to add some arguments at the beginning, you would have to construct your own slice with all of the arguments first, something like:
p := []string{"a", "b", "c"}
p2 := append([]string{"d"}, p...)
fmt.Println(path.Join(p2...))
which works alright and prints "d/a/b/c".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论