Golang Byte to String

Write a Golang program to convert the byte array to string. In this language, we have a string function that converts the byte array into a string. In this example, we declared a byte array and then used the string function (string(byteArray)) to convert it.

package main

import (
	"fmt"
)

func main() {

	byteArray := []byte{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}

	var strToConvert string

	strToConvert = string(byteArray)

	fmt.Println(strToConvert)
}
Golang Byte to String Conversion Program 1

Golang Program to Convert the Byte Array to String Example 2

package main

import (
    "fmt"
)

func main() {

    byteArray := []byte{0x43, 0x61, 0x66, 0xc3, 0xA9}

    strToConvert := string(byteArray)

    fmt.Println(strToConvert)

    strToConvert1 := string(byteArray[:])

    fmt.Println(strToConvert1)
}
Café
Café

In this example, we use the NewBuffer bytes function to convert the byte to string.

package main

import (
	"bytes"
	"fmt"
)

func main() {

	byteArray := []byte{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}

	var strToConvert string

	strToConvert = bytes.NewBuffer(byteArray).String()

	fmt.Println(strToConvert)
}
Hello World