To convert a string to a byte slice in Go, you can use the []byte
type conversion or the byte
package's Slice()
function. Here are two examples to achieve this:
str := "Hello, World!"
byteSlice := []byte(str)
In this code, the []byte(str)
expression converts the string str
to a byte slice.
Slice()
function from the bytes
package:import "bytes"
str := "Hello, World!"
byteSlice := bytes.Slice([]byte(str))
Here, the bytes.Slice()
function is used to convert the string str
to a byte slice.
Both of these methods will give you a byte slice containing the UTF-8 encoded representation of the original string.