Home >Backend Development >Golang >How to Convert a Fixed-Sized Byte Array to a String in Go?
Converting Sized Byte Array to String in Go
In Go, it is common to encounter situations where you need to convert a sized byte array to a string. This can arise, for instance, when working with hashed data such as MD5 digests.
Consider the following code snippet:
data := []byte("testing") var pass string var b [16]byte b = md5.Sum(data) pass = string(b)
Upon executing this code, you will encounter the following error:
cannot convert b (type [16]byte) to type string
The error stems from the fact that the string conversion expects a byte slice ([]byte), but the variable b is declared as a fixed-size array ([16]byte). To resolve this issue and convert the byte array to a string, you can utilize a byte slice derived from the byte array.
The following code demonstrates how to convert a sized byte array to a string correctly:
pass = string(b[:])
By using b[:], you are creating a byte slice that encompasses the entire byte array b. This byte slice can then be converted to a string as expected.
The above is the detailed content of How to Convert a Fixed-Sized Byte Array to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!