Kevin Burke
Kevin Burke

Reputation: 65024

Creating a byte slice with a known text string, in Golang

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:

  1. create a string with the values in memory
  2. create a byte slice
  3. copy the contents of the string into the byte slice (reallocating as necessary)

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

Answers (2)

James Henstridge
James Henstridge

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

peterSO
peterSO

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

Related Questions