我试图在 Go 中将可变参数从一个函数传递到另一个函数。基本上是这样的:
func CustomPrint(a ...interface{}) (int, error) {
// ...
// Do something else
// ...
return fmt.Print(a)
}
然而,当我这样做时,a
被打印成一个 slice ,而不是一个参数列表。即
fmt.Print("a", "b", "c") // Prints "a b c"
CustomPrint("a", "b", "c") // Print "[a b c]"
知道如何实现吗?
最佳答案
使用 slice 调用时使用...
:
package main
import "fmt"
func CustomPrint(a ...interface{}) (int, error) {
return fmt.Print(a...)
}
func main() {
CustomPrint("Hello", 1, 3.14, true)
}
关于go - 如何在 Go 中将可变参数从一个函数传递到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939940/