Convert string array to byte array in go

Issue

Given an string array which only contains single characters such as:

ex := [...]string{"a","o",".",".","2",".",".","9"}

is there a way to get a byte array with same content but with bytes instead of strings?

Solution

Use a conversion to convert each string to a []byte.

ex := [...]string{"a", "o", ".", ".", "2", ".", ".", "9"}
var ey [len(ex)][]byte
for i := range ex {
    ey[i] = []byte(ex[i])
}

Use this code if your intent is to get a byte array of the joined strings. This code only works when the strings are single ASCII characters.

ex := [...]string{"a", "o", ".", ".", "2", ".", ".", "9"}
var ey [len(ex)]byte
for i := range ex {
    ey[i] = ex[i][0]
}

Use this expression of you want to get a slice of bytes of the joined strings: []byte(strings.Join(ex[:], ""))

I don’t know the your context for doing this, but my guess is that it’s more appropriate to use a slice than an array:

ex := []string{"a", "o", ".", ".", "2", ".", ".", "9"}
ey := make([][]byte, len(ex))
for i := range ex {
    ey[i] = []byte(ex[i])
}

..

s := []byte(strings.Join(ex, ""))

Answered By – GastroHealth

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.