How to Convert between Strings and Byte Slices in Go
Converting between strings and byte slices in Go is a simple process, utilizing
the type conversion expression T(v)
to change value v
into type T
.
Converting a String to a Byte Slice
To convert a string into a byte slice, you can do the following:
func main() {
str := "A string"
fmt.Println([]byte(str))
}
[65 32 115 116 114 105 110 103]
Converting a Byte Slice to a String
Similarly, converting a byte slice back to a string is just as straightforward:
func main() {
b := []byte{65, 32, 115, 116, 114, 105, 110, 103}
fmt.Println(string(b))
}
A string
That’s all there is to converting between strings and byte slices in Go.
Thanks for reading, and happy coding!