Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way of converting array of strings to array of byte arrays

Tags:

go

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]]
like image 772
Adam Thomason Avatar asked Oct 10 '12 22:10

Adam Thomason


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can we convert string to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

What is the use of byte array in Java?

In Java, the string literals are stored as an array of Unicode characters. A byte array is an array of bytes. We can use a byte array to store the collection of binary data.


1 Answers

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]]
like image 66
Stephen Weinberg Avatar answered Oct 12 '22 06:10

Stephen Weinberg