2014-04-01 07:51
浏览 964

如何在Go中将[] interface {}转换为[]字符串?

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?

图片转代码服务由CSDN问答提供 功能建议

目前,我正在处理一些代码,其中涉及类型为 [ ] interface {}


  //  args的类型为[] interface {} 
name:= args [0] 
age:= args [1] // ect ... 

很好,但我希望能够使用 strings Join 函数,由于通常需要输入 [] string ,因此通常会出错 而不输入 [] interface {}

什么是能够使用 Join 的最合适的解决方案 函数,我猜想也许是某种转换吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doublel83422 2014-04-01 07:58

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

    打赏 评论

相关推荐 更多相似问题