将字符串数组转换为字节数组的惯用方法

huangapple go评论91阅读模式
英文:

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

huangapple
  • 本文由 发表于 2012年10月11日 06:28:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/12829410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定