Assigning a String to a Byte Array in Go

Clive B.
jump to solution

The Problem

You don’t know how to assign the value of a string to a byte array in Go.

The Solution

If you only need a byte slice, not an array, use the following one-liner:

[]byte("example string")

This works because strings in Go are effectively read-only slices of bytes.

If you need to assign a string to a fixed-length array, use copy:

package main

import "fmt"

func main() {
	var array [8]byte
	example := "example"

	copy(array[:], example)
	fmt.Println(array)
}

This prints:

[101 120 97 109 112 108 101 0]

The copy function fills the target array with the bytes contained in the source string.

It’s important to remember that if the string is longer than the array, copy will drop the remaining bytes.

Remember That Strings Are UTF-8

In the above example, we copied ASCII-compatible characters into a byte array and each character took one byte. However, UTF-8 strings can have up to 4 bytes per character.

For example, the ✨ emoji uses three bytes. If the example string contains a single ✨ emoji, all bytes from the source string will be assigned to the array:

package main

import "fmt"

func main() {
	var array [8]byte
	example := "✨"

	copy(array[:], example)
	fmt.Println(array)
}

Which prints:

[226 156 168 0 0 0 0 0]

However, if you set the variable to have three sparkles, the last byte (168) will be dropped from the target array:

func main() {
	var array [8]byte
	example := "✨✨✨"

	copy(array[:], example)
	fmt.Println(array)
}

Which prints:

[226 156 168 226 156 168 226 156]

Compare this to a byte slice, which retains all of the information from the three-sparkle string due to its variable length:

func main() {
	var array [8]byte
	example := "✨✨✨"

	fmt.Println([]byte(example))
}

Which prints:

[226 156 168 226 156 168 226 156 168]

When copying string values to an array, it’s important to consider your target array length and the bytes per character.

Unless you require an array, it’s easier to use a byte slice.

Further Reading

Go For Each Loops
Venter C.
Reading a file line by line in Go
Clive B.
Map Entries are Unaddressable
Evan Hicks
Checking if a string is empty in Go
Clive B.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry