How to Convert a Byte Array or Slice to a String

Sometimes a method will take a []byte as a parameter, but all you have is a string. Converting between a string and a []byte is actually just a matter of casting between them:

bytes := []byte(str)

or

str := string(bytes)

A longer example:

package main

import "fmt"

func giveMeBytes(bytes []byte) {
	// Print as bytes.
	fmt.Println(bytes)
	// Convert to a string and print.
	fmt.Println(string(bytes))
}

func main() {
	str := "Hello, world!"

	giveMeBytes([]byte(str))
}

Output:

[72 101 108 108 111 44 32 119 111 114 108 100 33]
Hello, world!

As useless as this program is, it shows a method that requires a slice of bytes, and how to pass a string into it using a cast (line 15). Within that method, the bytes are printed as a slice of bytes first, then as a string in the original form by casting it to a string in line 9.

Conclusion

Cast your net far and wide and you will catch more fish.

Leave a Reply

Your email address will not be published. Required fields are marked *