在Go语言中如何转换切片的切片?

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

Converting a slice of slices in Go?

问题

如何将这个字节切片的切片

[[105 100] [49]]

转换为字符串切片?

我尝试了

sliceOfStrings := []string(sliceOfByteSlices.([][]byte))

但是得到了一个

invalid type assertion: values.([][]byte) (non-interface type []interface {} on left)
英文:

How do I convert this slice of byte slices

[[105 100] [49]]

to slice of strings?

I tried

sliceOfStrings := []string(sliceOfByteSlices.([][]byte))

and got a

invalid type assertion: values.([][]byte) (non-interface type []interface {} on left)

答案1

得分: 2

你应该使用for循环,但是你可以稍微作弊一下,使用标准库。

byt := bytes.Join(a, []byte(sep))
str := strings.Split(string(byt), sep)

这里有一个可行的示例:https://play.golang.org/p/QzySUsRMg6

英文:

You should do for loop, but you can cheat a-little using std lib

byt := bytes.Join(a, []byte(sep))
str := strings.Split(string(byt), sep)

here is working example https://play.golang.org/p/QzySUsRMg6

答案2

得分: 2

你可以使用for循环来实现,代码如下:

package main

import "fmt"

func main() {
    var res []string
    arr := [][]byte{{105, 100}, {49}}

    for _, b := range arr {
        res = append(res, string(b))
    }
    fmt.Println(res)
}

在这里进行测试:http://play.golang.org/p/el4YXfFZpM

英文:

You can do it with a for-loop like so:

package main

import "fmt"

func main() {
	var res []string
	arr := [][]byte{{105, 100}, {49}}

	for _, b := range arr {
		res = append(res, string(b))
	}
	fmt.Println(res)
}

Test here: http://play.golang.org/p/el4YXfFZpM

huangapple
  • 本文由 发表于 2015年1月21日 02:57:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/28053105.html
匿名

发表评论

匿名网友

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

确定