I have this text which I would like to put into a byte slice:
s := "There are these two young fish swimming along and they happen to meet an older fish swimming the other way"
If I write
b := []byte("There are these two young fish swimming along and they happen to meet an older fish swimming the other way")
As I understand, at runtime this will:
I could convert each of the string values to their ASCII equivalent and create the byte slice directly:
b := []byte{84, 104, ... }
though this isn't very readable.
I understand that the example here is a little trivial and most computers can do this in a flash, but I'm curious about it. Does the compiler interpret []byte("blah")
and turn it into an efficient byte slice at compile time? Would the best solution change if the string included non-ASCII characters?
To convert a string to a byte slice in Go, use the standard []byte conversion expression []byte(string) . To convert a byte slice to a string, use the string([]byte) conversion.
Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points . Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111}
To convert String to Byte array in Golang, use the byte() function. A byte is an 8-bit unsigned int. The byte() function takes a string as an input and returns the array.
Byte. A byte in Go is an unsigned 8-bit integer. That means it has a limit of 0–255 in the numerical range. type byte = uint8. According to Go documentation, Byte is an alias for uint8 and is the same as uint8 in all ways.
Go embeds the string in the executable program as a string literal. It converts the string literal to a byte slice at runtime using the runtime.stringtoslicebyte
function.
If you are initialising a []byte
variable from a constant string, it looks like the compiler is smart enough not to create an intermediate string: instead, the backing array for the byte slice is initialised directly from static data rather than constructing a string variable first.
There is a data copy, but that is to be expected when constructing a mutable type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With