Sentry Answers>Go>

Assigning a String to a Byte Array in Go

Assigning a String to a Byte Array in Go

Clive B.

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:

Click to Copy
[]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:

Click to Copy
package main import "fmt" func main() { var array [8]byte example := "example" copy(array[:], example) fmt.Println(array) }

This prints:

Click to Copy
[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:

Click to Copy
package main import "fmt" func main() { var array [8]byte example := "✨" copy(array[:], example) fmt.Println(array) }

Which prints:

Click to Copy
[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:

Click to Copy
func main() { var array [8]byte example := "✨✨✨" copy(array[:], example) fmt.Println(array) }

Which prints:

Click to Copy
[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:

Click to Copy
func main() { var array [8]byte example := "✨✨✨" fmt.Println([]byte(example)) }

Which prints:

Click to Copy
[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

  • SentryGo Error Tracking and Performance Monitoring
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.