In Golang, converting a string to a byte array is straightforward and efficient, as strings and byte slices ([]byte
) are closely related. This conversion is commonly used when handling data in binary format, file I/O, or network operations.
The simplest way to convert a string to a byte array is by casting:
byteArray := []byte("your string here")
code example
package main
import "fmt"
func main() {
byteArray := []byte("your string here")
fmt.Println("s:", byteArray)
}
This converts the string into a byte slice, where each element represents a character in UTF-8 encoding. This process is fast since it doesn’t involve copying data; instead, it references the same memory. Converting from []byte
back to string
is just as easy: string(byteArray)
.
Leave a Comment