user1091856
user1091856

Reputation: 3158

Converting a slice of slices in Go?

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)

Upvotes: 0

Views: 548

Answers (2)

fredrik
fredrik

Reputation: 13550

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

Upvotes: 2

Uvelichitel
Uvelichitel

Reputation: 8490

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

Upvotes: 2

Related Questions