2015-12-10 184 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)。但你必须分别处理收藏中的每件物品。

相关问题