Reputation: 65024
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?
Upvotes: 15
Views: 21973
Reputation: 43949
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.
Upvotes: 4
Reputation: 166825
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.
Upvotes: 5