Converting [Size]byte to String in Go
When working with byte arrays in Go, it may be necessary to convert them to strings for further processing. Let's consider an example where you encounter an error while attempting to convert a sized byte array obtained from md5.Sum() to a string:
data := []byte("testing") var pass string var b [16]byte b = md5.Sum(data) pass = string(b)
This code will result in the following error:
cannot convert b (type [16]byte) to type string
The error occurs because the byte array b is fixed in size (16 bytes), while Go requires strings to be of variable length. To resolve this issue, you can refer to b as a slice instead of a fixed-size array:
pass = string(b[:])
By using slice syntax, you create a new string containing the bytes from b without specifying a fixed length. The result is a string that represents the bytes effectively. This approach allows you to convert any sized byte array to a string in Go.
The above is the detailed content of How to Convert a Fixed-Size Byte Array to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!