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.
[]byte(string)
We pass a string to the byte slice.
The slice that contains the bytes of all the characters of the string is returned.
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)}
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
is97–122
, the stringabcdef
gets converted to[97 98 99 100 101 102]
when we pass it to a byte slice.