Golang String to Byte Array

Write a Golang program to convert the given string to the byte array. The byte method converts the string to a byte array. In this example, []byte(strToConvert) will convert the string to a byte array.

package main

import (
    "fmt"
)

func main() {
    var strToConvert string

    strToConvert = "Hello World"

    byteString := []byte(strToConvert)
    fmt.Println(byteString)
}
Golang or go String to Byte Array Conversion

Golang Program to Convert a String to Byte Array using copy function

In this programming language, the copy function will copy the string to a byte array. So, we declared a byte array and used the copy function to copy the string to the byte array. If you don’t know the string length, replace 16 with len(strToConevrt).

package main

import (
	"fmt"
)

func main() {
	var strToConvert string

	strToConvert = "Tutorial Gateway"

	byteString := make([]byte, 16)

	copy(byteString, strToConvert)

	fmt.Println(byteString)

	byteString1 := make([]byte, 16)

	copy(byteString1[:], strToConvert)

	fmt.Println(byteString1)
}
[84 117 116 111 114 105 97 108 32 71 97 116 101 119 97 121]
[84 117 116 111 114 105 97 108 32 71 97 116 101 119 97 121]