# Go Assign a String to a Byte Array or Byte Slice

> Convert a Go string to a byte slice directly with a type conversion, or use the copy function to fill a fixed-length byte array while handling UTF-8

**URL:** https://sentry.io/answers/assigning-a-string-to-a-byte-array-in-go/

---

## 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:

```go
[]byte("example string")
```

This works because strings in Go are [effectively read-only slices of bytes](https://go.dev/blog/strings#what-is-a-string).

If you need to assign a string to a fixed-length array, use [`copy`](https://pkg.go.dev/builtin#copy):

```go
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:

```go
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:

```go
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:

```go
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

- The [Go `slices` package](https://pkg.go.dev/slices) documentation
- The [Strings, bytes, runes and characters in Go](https://go.dev/blog/strings) blog post
- The [UTF-8](https://en.wikipedia.org/wiki/UTF-8) Wikipedia article

---

*Source: [sentry.io/answers/assigning-a-string-to-a-byte-array-in-go/](https://sentry.io/answers/assigning-a-string-to-a-byte-array-in-go/)*
