Avatar ·

How to convert a string to a byte slice ([]byte) in Go?

Hi everyone! I just started learning Go and encountered a problem that seems elementary, but I can't find the right solution.

\n\n

I have a string:

\n\n
s := "Hello, World!"\n
\n\n

I need to convert it to a byte slice []byte to pass to a function that accepts exactly this type. I tried several options, but they cause compilation errors or panic.

\n\n

Here's what I tried:

\n\n
package main\n\nimport "fmt"\n\nfunc main() {\n    s := "Hello, World!"\n    // Option 1: directly\n    var b []byte = s\n    fmt.Println(b)\n\n    // Option 2: via make and copy\n    b2 := make([]byte, len(s))\n    b2 = s\n    fmt.Println(b2)\n}\n
\n\n

The first option gives: cannot use s (type string