英文:
How could I convert an []interface{} into a []string in Go?
问题
我目前正在处理一段代码,其中涉及到一个类型为[]interface{}
的变量。
它包含了一些值,我可以通过以下方式轻松访问:
// 假设args的类型为[]interface{}
name := args[0]
age := args[1] //等等...
这样做是可以的,但是我想要能够使用strings
包中的Join
函数,但通常会出错,因为它需要的是[]string
类型而不是[]interface{}
类型。
为了能够使用Join
函数,最合适的解决方案是什么,我猜可能需要进行某种类型的转换?
英文:
I'm currently working with a bit of code at the moment, that involves a var with type []interface{}
It has values within it, that I could easily access like so:
//given that args is of type []interface{}
name := args[0]
age := args[1] //ect...
This is fine, but I'd like to be able to use the strings
Join
function, and it would typically error due to it requiring type []string
and not type []interface{}
.
What would be the most appropriate solution to be able to use the Join
function, I'd guess maybe some sort on conversion?
答案1
得分: 4
你需要构建一个类型为[]string
的新数组,以便使用strings.Join
函数:
import "fmt"
import "strings"
func main() {
s1 := []interface{}{"a", "b", "c"}
s2 := make([]string, len(s1))
for i, s := range s1 {
s2[i] = s.(string)
}
fmt.Println(strings.Join(s2, ", "))
}
请参考相关的Golang FAQ条目:我可以将[]T
转换为[]interface{}
吗?
英文:
You need to construct a new array of type []string
in order to use strings.Join
:
import "fmt"
import "strings"
func main() {
s1 := []interface{}{"a", "b", "c"}
s2 := make([]string, len(s1))
for i, s := range s1 {
s2[i] = s.(string)
}
fmt.Println(strings.Join(s2, ", "))
}
See the related Golang FAQ entry: can I convert a []T to an []interface{}?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论