2017-02-26 39 views
3

我想調用一個可變參數函數並動態地組成參數。以fmt.Printf()爲例。如果我有一個structgolang:variadic函數參數的動態組合

type Foo struct { 
    a int 
    b string 
} 

我想打電話fmt.Printf(foo.a, foo.b).但是,如果我有另一個Bar struct有3場,我想打電話給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中實現這一點?

+0

,你想創建一個接受任何種類結構的功能?如果那麼簡單使用''''interface'' –

+0

@GujaratSantana是的。但func(params ... interface {}' – lang2

+0

'''interface''不能被''interface'接受''func boo(params ... interface {}){}'似乎解決了你的問題問題。 – Rodrigo

回答

4

使用省略號操作

slice := []Type{Type{}, Type{}} 
call(slice...) 

的功能

func(arg ...Type) {}