5

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]]

1 Answer 1

12

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]]
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't it slightly more than a matter of style? The OP's code will, depending upon the size of the input, ping the allocator several times. Yours will ask for one glob of memory and be done with it. (Of course, OP could just use make([][]byte, 0, len(input)) instead of a composite literal...)
Yes, it would allocate a couple of time if he does it his way. However, it is unlikely to make much difference because strings are really small. You are right that using make() and setting a sane cap would decrease the number of allocations the same way my example does.
Agreed, that's what I disliked about the repeated calls to append().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.