To convert a byte array to a string in Go, use the built-in string() function. Here’s an example:
package main
import “fmt”
func main() {
byteArray := []byte{72, 101, 108, 108, 111} // ASCII for “Hello”
str := string(byteArray)
fmt.Println(str) // Output: Hello
}
The string() function efficiently converts the byte slice to a string. This is useful when dealing with encoded data like UTF-8 or ASCII. Note that improper encoding or non-textual data may result in unexpected output. For custom encoding, use packages like encoding/json or encoding/base64.