英文:
How to pass variadic parameters from one function to another in Go
问题
我正在尝试在Go中将可变参数从一个函数传递到另一个函数。基本上像这样:
func CustomPrint(a ...interface{}) (int, error) {
// ...
// 做其他事情
// ...
return fmt.Print(a)
}
然而,当我这样做时,a
被打印为一个切片,而不是参数列表。例如:
fmt.Print("a", "b", "c") // 打印 "a b c"
CustomPrint("a", "b", "c") // 打印 "[a b c]"
有什么办法可以实现这个?
英文:
I'm trying to pass variadic parameters from one function to another in Go. Basically something like this:
func CustomPrint(a ...interface{}) (int, error) {
// ...
// Do something else
// ...
return fmt.Print(a)
}
However when I do this a
is printed like a slice, not like a list of arguments. i.e.
fmt.Print("a", "b", "c") // Prints "a b c"
CustomPrint("a", "b", "c") // Print "[a b c]"
Any idea how to implement this?
答案1
得分: 7
使用切片时使用...
:
package main
import "fmt"
func CustomPrint(a ...interface{}) (int, error) {
return fmt.Print(a...)
}
func main() {
CustomPrint("Hello", 1, 3.14, true)
}
英文:
Use ...
when calling with a slice:
package main
import "fmt"
func CustomPrint(a ...interface{}) (int, error) {
return fmt.Print(a...)
}
func main() {
CustomPrint("Hello", 1, 3.14, true)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论