How to convert a Golang string into bytes

In this shot, we will learn how to convert a string into a slice of bytes.

We can pass a string to a byte slice data type, which will return a slice that will contain the bytes of each character of the string.

Syntax

[]byte(string)

Parameters

We pass a string to the byte slice.

Return value

The slice that contains the bytes of all the characters of the string is returned.

Code

In the code snippet below, we will convert the string abcdef into a slice of bytes:

package main
//import format package
import(
"fmt"
)
//program execution starts here
func main(){
//declare a string
s := "abcdef"
//convert string to bytes
b:= []byte(s)
//display the slice of bytes
fmt.Println(b)
}

Code explanation

In the code snippet above:

  • In line 5, we import the fmt package, which is useful for printing statements.

  • In line 9, the program execution starts from the main() function in Golang.

  • In line 12, we declare and initialize a string with the variable name s.

  • In line 15, we pass the string s to the byte slice to convert it into a slice of bytes. We assign this slice of bytes to variable b.

  • In line 18, we display the slice of bytes.

Note: Since the ASCII code for a–z is 97–122, the string abcdef gets converted to [97 98 99 100 101 102] when we pass it to a byte slice.