Golang String to Byte Array

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

package main

import (
    "fmt"
)

func main() {
    var strToConvert string

    strToConvert = "Hello World"

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

Golang Program to Convert a String to Byte Array Example 2

In Go programming, the copy function will copy the string to byte array. So, we declared a byte array and used the copy function to copy the string to 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]