Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

encoding

go

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?

like image 222
Kevin Burke Avatar asked Sep 05 '14 18:09

Kevin Burke


People also ask

How do you convert a string slice to a byte slice in Golang?

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.

What is a byte slice in Golang?

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}

How do I create a byte array in Golang?

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.

What is a byte string in Golang?

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.


2 Answers

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.

like image 150
peterSO Avatar answered Oct 27 '22 09:10

peterSO


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.

like image 31
James Henstridge Avatar answered Oct 27 '22 11:10

James Henstridge