In this section, we're going to learn how to convert a byte array into a string:
Note
The most important thing you need to know about this tutorial is that in Go, string variables are just a slice of bytes. Therefore, it is really easy to convert a byte array into a string value and a string value into a byte array.
- Let's see how we can start this. Imagine that you have a
helloWorldByte
array; currently, it is a literal byte array, but you can derive it from any stream, such as a network or a file:
package main import "fmt" func main(){ helloWorldByte := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100} fmt.Println(string(helloWorldByte)) }
- We also have the string construct, which makes it really easy to convert a byte array into a string representation of it. We are going to use
fmt.Println
for the string representation of thishelloWorldByte
and run the code. - So, let's run the code and check the output: