如何在Go中将可变参数从一个函数传递到另一个函数

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

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)
}

huangapple
  • 本文由 发表于 2013年7月30日 14:40:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/17939940.html
匿名

发表评论

匿名网友

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

确定