How to convert a string to a byte slice in Golang?

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:

  1. Using type conversion:
str := "Hello, World!" byteSlice := []byte(str)

In this code, the []byte(str) expression converts the string str to a byte slice.

  1. Using the 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.