I need to convert an array of strings to an array of byte arrays. This code works, but the repeated append
seems distasteful to me. Is there a better way?
input := []string{"foo", "bar"}
output := [][]byte{}
for _, str := range input {
output = append(output, []byte(str))
}
fmt.Println(output) // [[102 111 111] [98 97 114]]
No matter what, you will need to create a new [][]byte
and loop over the []string
. I would avoid using append by using the following code, but it is really all a question of style. Your code is perfectly correct.
input := []string{"foo", "bar"}
output := make([][]byte, len(input))
for i, v := range input {
output[i] = []byte(v)
}
fmt.Println(output) // [[102 111 111] [98 97 114]]