Latest Code Tutorials

How to Convert Golang String to Byte Array

In Golang, to convert a string to a byte array, you get a slice containing the string’s bytes. In Go, a string is, in effect, a read-only slice of bytes. It’s essential to state right up front that a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format. As far as the content of a string is concerned, it is precisely equivalent to a slice of bytes.

Golang String to Byte Array

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.

In Golang, we often use byte slices. Here is a Go example that shows how to convert a string to a byte array.

package main

import "fmt"

func main() {
	str := "MBB$"
	data := []byte(str)


go run hello.go
[77 66 66 36]

In the code, first, we defined the string MBB$ and then converted that string into a slice of bytes.

Then use the fmt.Println() method to print the array of bytes.

Golang bytes.Index()

Here we import the “bytes” package at the top (in the import statement). We call bytes.Index() to locate the sequence with the byte values.

See the following code.

// hello.go

package main

import (

func main() {
	values := []byte("Pug")

	// Search for this byte sequence.
	result := bytes.Index(values, []byte("g"))

	// This byte sequence is not found.
	result = bytes.Index(values, []byte("Dog"))
	if result == -1 {
		fmt.Println("Dog not found")


go run hello.go
Dog not found

Golang strings.Index() method, bytes.Index() function returns the index if a sequence matches. Otherwise, it returns -1.

In the first example, we find g matches with Pug, so it returns the index of g in Pug, which is 2 because the index starts with 0.

In the second example, we don’t find the Dog sequence in Pug; that is why it returns Dog not found.

Golang Copy string to a byte slice

Golang copy() is an inbuilt method that can copy the string into a byte slice.

See the following code.

// hello.go

package main

import "fmt"

func main() {
	// Create an empty byte slice of length 4.
	values := make([]byte, 4)
	// Copy string into bytes.
	animal := "pug"
	copied := copy(values, animal)


go run hello.go
[112 117 103 0]

Here we create an empty 4-element byte slice. Then we copy a three-element string into it.

That’s it for this tutorial.

See also

Golang json to map

Golang slice to string

Golang int to string

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.