2015-12-10 239 views
-1

我想在字符串列表中傳遞一個通用參數,但不確定它是否可能。我有解決方法,但覺得我只是無法得到正確的語法。從字符串列表到字符串中的接口列表

package main 

import "fmt" 

func Set(otherFields ...interface{}) { 
    fmt.Printf("%v", otherFields) 
} 

func main() { 
    a := []string {"Abc", "def", "ghi"} 
    Set(a) // incorrect behavior because a passed through as a list, rather than a bunch of parameters 
// Set(a...) // compiler error: cannot use a (type []string) as type []interface {} in argument to Set 
// Set([]interface{}(a)) // compiler error: cannot convert a (type []string) to type []interface {} 
    // This works but I want to do what was above. 
    b := []interface{} {"Abc", "def", "ghi"} 
    Set(b...) 
} 
+0

請參閱[常見問題](https://golang.org/doc/faq#convert_slice_of_interface)。 –

回答

3

你必須單獨處理每個字符串。你不能只投射整個集合。這是一個例子。

package main 

import "fmt" 

func main() { 
    a := []string {"Abc", "def", "ghi"} 
    b := []interface{}{} // initialize a slice of type interface{} 

    for _, s := range a { 
    b = append(b, s) // append each item in a to b 
    } 
    fmt.Println(len(b)) // prove we got em all 

    for _, s := range b { 
    fmt.Println(s) // in case you're real skeptical 
    } 

} 

https://play.golang.org/p/VWtRTm01ah

正如你所看到的,沒有轉換是必要的,因爲inferface{}類型的集合將接受任何類型(所有類型實現了空接口Go equivalent of a void pointer in C)。但你必須分別處理收藏中的每件物品。

相關問題