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\nI have a string:
\n\ns := "Hello, World!"\n\n\nI 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.
Here's what I tried:
\n\npackage 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\nThe first option gives: cannot use s (type string
No answers yet.
Log in to leave an answer