golang:可变参数函数参数的动态组合

lan*_*ng2 3 go

我想调用一个可变参数函数并动态组合参数。以fmt.Printf()为例。如果我有struct

type Foo struct {
   a int
   b string
}
Run Code Online (Sandbox Code Playgroud)

我想打电话fmt.Printf(foo.a, foo.b).但是如果我有另一个Bar struct有 3 个字段的,我想打电话给fmt.Printf(bar.a, bar.b, bar.c).

所以我想写一个这样的函数:

func MyPrint(obj interface{})
Run Code Online (Sandbox Code Playgroud)

并且能够使用MyPrint(foo)or调用它,MyPrint(bar)代码将自动找出foo有 2 个字段并执行:

...
fmt.Printf(foo.a, foo.b)
Run Code Online (Sandbox Code Playgroud)

bar 有 3 个字段并且做

...
fmt.Printf(bar.a, bar.b, bar.c)
Run Code Online (Sandbox Code Playgroud)

在 Python 中,您可以执行类似call(*list). 我如何在 Go 中实现这一目标?

Grz*_*Żur 5

使用省略号运算符

slice := []Type{Type{}, Type{}}
call(slice...)
Run Code Online (Sandbox Code Playgroud)

对于功能

func(arg ...Type) {}
Run Code Online (Sandbox Code Playgroud)