How to convert between strings and byte slices in Go
If you want to modify a string, it may be useful to convert it to a byte slice first since strings are immutable while byte slices may be modified. A conversion from string to byte slice (or vice versa) will yield the exact same result. The data remains the same between conversions.
The syntax for converting between strings and byte slices in Go is fairly
straightforward. In both cases, all you need to do is use the expression T(v)
which converts the value v
to the type T
.
Convert a string to byte slice
Here’s how you can convert a string to a byte slice in Go:
func main() {
str := "A string"
fmt.Println([]byte(str)) // [65 32 115 116 114 105 110 103]
}
Convert a byte slice to a string
Here’s how to convert a byte slice to a string:
func main() {
b := []byte{65, 32, 115, 116, 114, 105, 110, 103}
fmt.Println(string(b))
}
Conclusion
That’s all there is to converting between strings and byte slices in Go. You may also be interested in reading about different string concatenation strategies in Go.
Thanks for reading, and happy coding!