How could I convert an []interface{} into a []string in Go?

huangapple go评论80阅读模式
英文:

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{}?

huangapple
  • 本文由 发表于 2014年4月1日 15:51:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/22779787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定