GoLang Byte Array to String

There are three easy ways to convert byte array to string in GoLang.

1. Byte Array to String using Slice

This is the easiest way to convert the byte array to string. We can pass the byte array to the string constructor with slicing. Let’s look at a simple example.

package main

import (
	"fmt"
)

func main() {
	byteArray := []byte{'G', 'O', 'L', 'A', 'N', 'G'}
    	str1 := string(byteArray[:])
    	fmt.Println("String =",str1)
}

Output: String = GOLANG

2. Convert byte array to string using bytes package

We can use the bytes package NewBuffer() function to create a new Buffer and then use the String() method to get the string output.

package main

import (
	"fmt"
	"bytes"
)

func main() {
	byteArray := []byte{'H', 'E', 'L', 'L', 'O'}
    	str1 := bytes.NewBuffer(byteArray).String()
    	fmt.Println("String =",str1)
}

Output: String = HELLO

3. Using fmt.Sprintf() function to convert byte array to string

This is a workaround way to convert byte array to string. The Sprintf() function is a bit slow but we can use it to convert byte array to string.

package main

import (
	"fmt"
)

func main() {
	byteArray := []byte{'J', 'A', 'N', 'E'}
    	str1 := fmt.Sprintf("%s", byteArray)
    	fmt.Println("String =",str1)
}

Output: String = JANE

Conclusion

We looked at three different ways to convert the byte array to String in GoLang. I personally prefer the first method because it’s simple and doesn’t need to import any other package.

References