今天在嘗試用go寫一個簡單的orm的時候 發現 在調用可變參數函數時,不是總能使用省略號將一個切片展開,有時候編譯器可能會報錯 再此用幾個簡單的例子做爲說明app
當不太肯定數據類型的時候咱們一般採用空接口函數
tests1(789) fmt.Println("-------------") tests1("789")
func tests1(arg interface{}) { fmt.Println("value:", arg) fmt.Println("type:", reflect.TypeOf(arg).Name()) }
輸出結果code
value: 789 type: int ------------- value: 789 type: string
在使用相同類型的可變入參時orm
tests([]string{"4", "5", "6"}...)
func tests(args ...string) { for i, v := range args { fmt.Println(i, "----", v) } }
輸出結果接口
0 ---- 4 1 ---- 5 2 ---- 6
當使用interface{}做爲可變入參時編譯器
func testParams(args ...interface{}) { for i, v := range args { if s, ok := v.(string); ok { fmt.Println("----", s) } if s, ok := v.([]string); ok { for i, v := range s { fmt.Println(i, "[]----", v) } } fmt.Println(i, v) } }
出現錯誤string
cannot use []string literal (type []string) as type []interface {} in argument to testParams
當看到這裏時候答案已經露出水面了
這裏提供兩種解決方案it
第一種方法編譯
s := []string{"4", "5", "6"} var d []interface{} = []interface{}{s[0], s[1], s[2]} testParams(d...)
結果test
---- 4 0 4 ---- 5 1 5 ---- 6 2 6
第二種方法
s := []string{"4", "5", "6"} var d []interface{} d = append(d, s) testParams(d...)
結果
0 []---- 4 1 []---- 5 2 []---- 6 0 [4 5 6]
總結: 在使用interface{}做爲可變入參時 傳入的參數要作類型轉換