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 packageimport("fmt")//program execution starts herefunc main(){//declare a strings := "abcdef"//convert string to bytesb:= []byte(s)//display the slice of bytesfmt.Println(b)}
Code explanation
In the code snippet above:
-
In line 5, we import the
fmtpackage, 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
sto the byte slice to convert it into a slice of bytes. We assign this slice of bytes to variableb. -
In line 18, we display the slice of bytes.
Note: Since the ASCII code for
a–zis97–122, the stringabcdefgets converted to[97 98 99 100 101 102]when we pass it to a byte slice.