英文:
Idiomatic way of converting array of strings to array of byte arrays
问题
我需要将一个字符串数组转换为字节数组数组。这段代码可以工作,但是我觉得重复的append
看起来不太好。有没有更好的方法?
input := []string{"foo", "bar"}
output := [][]byte{}
for _, str := range input {
output = append(output, []byte(str))
}
fmt.Println(output) // [[102 111 111] [98 97 114]]
英文:
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
得分: 12
无论如何,您都需要创建一个新的[][]byte
并循环遍历[]string
。我建议使用以下代码来避免使用append,但这完全是一个风格问题。您的代码是完全正确的。
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]]
英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论