Assigning String to Byte Array
In your code, you've successfully assigned the string "abc" to a byte array using a range loop. However, there is a simpler and equally secure method to achieve the same result.
Using []byte() Function
Instead of manually converting each character to a byte and assigning it to the array, you can use the []byte() function to perform the conversion. This function returns a slice of bytes representing the contents of the string.
[]byte("Here is a string....")
This code will create a byte array with the following values:
[72 101 114 101 32 105 115 32 97 32 115 116 114 105 110 103 46 46 46]
Using this method is concise and ensures the correct conversion of characters to bytes. It is important to note that the []byte() function returns a slice of bytes, which is not the same as an array. If you require an array, you can use the copy() function to copy the slice into an array.
var arr [20]byte copy([]byte("Hello, world!"), arr[:])
This code will copy the bytes from the slice into the first 20 elements of the array arr.
The above is the detailed content of How Can I Efficiently Convert a String to a Byte Array in Go?. For more information, please follow other related articles on the PHP Chinese website!