在Go语言中调用可变参数函数。

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

Call a variadic function in Go

问题

我有一段代码,在其中调用了filepath.Join,如下所示的程序所描述。
然而,我遇到了一个错误。

程序:

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	myVal := joinPath("dir1", "dir2")
	fmt.Println(myVal)
}

func joinPath(dirs ...string) string {
	return filepath.Join("mydir", dirs...)
}

错误:
./prog.go:16:32: 调用filepath.Join时参数过多 拥有 (string, []string) 期望 (...string)

虽然我知道这是一个合法的错误,但我该如何使用Join方法连接路径并设置默认的父目录呢?

英文:

I have code where I am calling filepath.Join as described in the following program.
However, I see an error

Program:

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	myVal := joinPath("dir1", "dir2")
	fmt.Println(myVal)
}

func joinPath(dirs ...string) string {
	return filepath.Join("mydir", dirs...)
}

Error:
./prog.go:16:32: too many arguments in call to filepath.Join
have (string, []string)
want (...string)

While I know this is a legitimate error, how do I join the path with a default parent directory using Join

答案1

得分: 2

你不能在可变参数中混合使用切片和显式元素,详细信息请参考https://stackoverflow.com/questions/28625546/mixing-exploded-slices-and-regular-parameters-in-variadic-functions/28626170#28626170

然而,在你的特殊情况下,你可以调用filepath.Join()两次,得到相同的结果:

func joinPath(dirs ...string) string {
    return filepath.Join("mydir", filepath.Join(dirs...))
}

你也可以准备一个包含所有元素的切片,并像这样传递:

func joinPath(dirs ...string) string {
    return filepath.Join(append([]string{"mydir"}, dirs...)...)
}

两种方法都会返回并输出以下结果(可以在Go Playground上尝试):

mydir/dir1/dir2
英文:

You can't mix a slice and explicit elements for a variadic parameter, for details, see https://stackoverflow.com/questions/28625546/mixing-exploded-slices-and-regular-parameters-in-variadic-functions/28626170#28626170

However, in your special case you may call filepath.Join() twice, and get the same result:

func joinPath(dirs ...string) string {
	return filepath.Join("mydir", filepath.Join(dirs...))
}

You may also prepare a slice with all elements, and pass that like this:

func joinPath(dirs ...string) string {
	return filepath.Join(append([]string{"mydir"}, dirs...)...)
}

Both will return and output (try them on the Go Playground):

mydir/dir1/dir2

huangapple
  • 本文由 发表于 2022年6月30日 02:20:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/72806140.html
匿名

发表评论

匿名网友

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

确定