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

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

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

huangapple
  • 本文由 发表于 2017年2月26日 11:16:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/42464350.html
匿名

发表评论

匿名网友

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

确定