英文:
Casting From a list of strings to a list of interface in go
问题
我想在Go语言中将字符串列表作为泛型参数传递,但不确定是否可能。我有一些解决方法,但感觉我只是无法正确使用语法。
package main
import "fmt"
func Set(otherFields ...interface{}) {
fmt.Printf("%v", otherFields)
}
func main() {
a := []string {"Abc", "def", "ghi"}
Set(a) // 错误的行为,因为a被作为一个列表传递,而不是一堆参数
// Set(a...) // 编译错误:无法将a(类型[]string)作为Set的参数类型[]interface{}
// Set([]interface{}(a)) // 编译错误:无法将a(类型[]string)转换为类型[]interface{}
// 这个方法可以工作,但我想做上面的那个方法。
b := []interface{} {"Abc", "def", "ghi"}
Set(b...)
}
以上是要翻译的内容。
英文:
I want to pass in a list of strings as generic parameters in go, but not sure if its possible. I have workarounds but feel like I'm just not able to get syntax correct.
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...)
}
答案1
得分: 3
你必须逐个处理每个字符串。不能只是将整个集合进行强制转换。这里有一个示例:
package main
import "fmt"
func main() {
a := []string {"Abc", "def", "ghi"}
b := []interface{}{} // 初始化一个类型为 interface{} 的切片
for _, s := range a {
b = append(b, s) // 将 a 中的每个项追加到 b 中
}
fmt.Println(len(b)) // 证明我们已经获取了所有项
for _, s := range b {
fmt.Println(s) // 以防你真的怀疑
}
}
如你所见,不需要进行强制转换,因为类型为 interface{}
的集合将接受任何类型(所有类型都实现了空接口 https://stackoverflow.com/questions/8996771/go-equivalent-of-a-void-pointer-in-c)。但你确实需要逐个处理集合中的每个项。
英文:
You have to deal with each string individually. You can't just cast the whole collection. Here's an example;
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
As you can see, no cast is necessary because the collection of type inferface{}
will accept any type (all types implement the empty interface https://stackoverflow.com/questions/8996771/go-equivalent-of-a-void-pointer-in-c). But you do have to deal with each item in collection individually.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论