Golang Program to to convert string to byte array

March 17, 2022, Learn eTutorial

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to convert the string to byte array

To convert a sting to a byte array we need to translate the sequence of chjaracters into a equence of bytes. For this translation we use an instance of charset. This specifies a mapping between a sequence of characters and a sequence of bytes.  A charset or character set refers to the composite number of different characters that are being used and supportedby the computer hardware and software. 

How to convert the string to byte array in the GO Program

 Here we are showing how to convert the string to byte array in the Go language. Here variable str is holding the string to be converted. And variable byteStr for holding the result. Finally, the string is converted using []byte(str) and print the result. Given below are the steps which are used in the Go program. 


STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the string variable str

STEP 4: Consider variable byteStr for holding the result

STEP 5: The string is converted using []byte(str)

STEP 6: Finally print the variable byteStr using fmt.Println()


Golang Source Code

                                          package main

import (

func main() {

    var str string
    str = "Hello World"
    byteStr:= []byte(str)


[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]