英文:
golang: dynamic composition of variadic function parameter
问题
我想调用一个可变参数函数,并动态地组合参数。以fmt.Printf()为例。如果我有一个结构体:
type Foo struct {
a int
b string
}
我想调用fmt.Printf(foo.a, foo.b)。但是如果我有另一个有3个字段的Bar结构体,我想调用fmt.Printf(bar.a, bar.b, bar.c)。
所以我想写一个这样的函数:
func MyPrint(obj interface{})
并能够用MyPrint(foo)或MyPrint(bar)来调用它,代码将自动找出foo有2个字段,并执行:
...
fmt.Printf(foo.a, foo.b)
bar有3个字段,并执行:
...
fmt.Printf(bar.a, bar.b, bar.c)
在Python中,你可以使用call(*list)来实现这个功能。在Go语言中,你可以如何实现呢?
英文:
I'd like to call a variadic function and compose the parameter dynamically. Take fmt.Printf() for example. if I have a struct:
type Foo struct {
a int
b string
}
I'd like to call fmt.Printf(foo.a, foo.b). But if I have another Bar struct with 3 fields, I'd like to call fmt.Printf(bar.a, bar.b, bar.c).
So I'd like to write a function like this:
func MyPrint(obj interface{})
and be able to call it with MyPrint(foo) or MyPrint(bar) and the code will automatically figure out that foo has 2 fields and do:
...
fmt.Printf(foo.a, foo.b)
bar has 3 fields and do
...
fmt.Printf(bar.a, bar.b, bar.c)
In Python you can do something like call(*list). How can I achieve this in Go?
答案1
得分: 8
使用省略号操作符
slice := []Type{Type{}, Type{}}
call(slice...)
对于函数
func(arg ...Type) {}
英文:
Use ellipsis operator
slice := []Type{Type{}, Type{}}
call(slice...)
for function
func(arg ...Type) {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论